What is the relationship between matrix position to array index of corresponding matrix?

4.7k Views Asked by At

I want to know the exact relationship between matrix position and array index, where array contains the matrix data in each row appended format.

For example: I had a matrix of $3 \times4$ as follows:

[
 [a, b, c, d],
 [e, f, g, h],
 [i, j, k, l],
]

And its array representation as follows:

[a, b, c, d, e, f, g, h, i, j, k, l,]

So if I say the position of item c is $[0,2]$ (by taking starting index as $[0,0]$) and then the position of c in array is 2, what is the relationship between these two indices, for any item in matrix?

Here I know the number of rows(nR) and column(nC) of matrix.

I need a relationship between these to position, so that I can create matrix position using array index and array index using matrix position.

Thanks you for all your valuble informations.
PS:Provide me some good tutorials to understand these things from basic levels.

3

There are 3 best solutions below

8
On BEST ANSWER

The position in array is exactly equal to the number of elements before it if you start from $0$. The elements before it consist of two sets, one is the set of elements in the previous rows, the other is the previous elements in the current row. Let's name them $S_1$ and $S_2$.

Suppose the index in the matrix is $(i,j)$. There are then $i$ rows before it. So number of those elements will be $S_1=i\cdot nC$ where $nC$ is the number of elements in a row.

The number of elements before it in the current row is exactly $S_2=j$.

So the position in array is $i\cdot nC + j$.

REVERSE: S = arrayIndex row = (S+1) / Cn col = (S+1) % Cn -1

2
On

if you have an $m \times n $ matrix $A$ and you write(row major) is as an array $a$ by putting the row zero, row 1, etc, then $$a[i*n + j] = A[i,j],0 \le i < m, 0 \le j < n.$$

here inverse mapping going from vector index to matrix index: $$A[n*int(k/n) ,k\%n] = a[k], 0 \le k < m*n$$

0
On

The operation to turn a matrix or multidimensional array into a one dimensional array is called vectorization and it is not unique. There is $$n! = n\cdot (n-1)\cdots 2\cdot 1$$ ways to do it if the total number of data points is $n$. I.e. number of permutations, which is a very fast growing function. Extremely many possibilities even for small data sets.

How it is done in practice depends totally on the programming langugage, memory architecture, person who wrote the software you are using and so on.

Just to give an example of one of many ways is the famous zig-zag scanning pattern in Jpeg image coding standard : zig-zag


edit: In my enthusiasm to give a general answer I forgot your particular example. Here you need integer division (rounding down) and modulo (rest after having rounded down).

The quotient when dividing the array index with the number of columns is the row. The rest or modulus is the column.