Assume a 3 x 3 grid, but the elements are actually contained in a zero-based index array. So I know if I'm on element 5, I'm in row 2, and if I'm on element 7 then I'm in row 3. How would I actually calculate this? Please feel free to modify the title's terminology if I'm not using it correctly. Also, I would very much appreciate the logic used to determine the formula for the answer, as I'm not a mathematician.
What row am I on in a matrix if I only have the column index of an element, and the total number of columns and rows?
2
$\begingroup$
matrices
-
0Sorry, yes, a 3 x 3 grid = 9 elements. I will change. – 2011-10-27
2 Answers
1
The logic used is fairly simple. If you have a 3 by 3 grid, starting at 0, the elements would look as:
0 1 2
3 4 5
6 7 8
You count from left to right, until the number of columns matches the number of columns the grid has, then start again with the next row.
Mathematically, the row is floor(elementNumber / numberOfRows) I.E.: element 4 would be floor(4 / 3) = 1.33 = 1; which is actually row 2 (0 indexed remember?)
The Column would be elementNumber mod numberofColumns. IE, element 4: 4 mod 3 = 1; which is actually column 2 (0 indexed)