0

I had a 2D array (matrix) and its array(1D) representation, I want to know what is the relationship between the [x][y] position of an item in matrix with [index] of the corresponding item array representation.

Explanation: Lets say I had matrix of 3x4 size:

Matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Array = [1,2,3,4,5,6,7,8,9,10,11,12]

The position of item '6' in matrix is [1][1] and its position in array is [5].

So what I want to know is what is the relationship b/w [1][1] and [5] in matrix of size 3x4.

Thanks for the suggestions and replies.

PS: I need the mathamatic logic behind it, not a function in any languages (matlab) to do this functionality.

Dipak
  • 6,532
  • 8
  • 63
  • 87

1 Answers1

3

MATLAB indexes values column-wise, starting at position 1, not zero. Thus in a matrix:

A =
     1     2     3     4
     5     6     7     8
     9    10    11    12

A(:).'   %// Straighten it out to column vector and transpose (to make it a row) 
ans =
     1     5     9     2     6    10     3     7    11     4     8    12

So, A(1) = 1, A(2) = 5 etc. If you have a linear index, for instance 7, A(7) = 3, and want the indexes on the form [row , col], you can use sub2ind like this:

ind = 7
[row, col] = ind2sub(size(A), ind)
row =
     1
col =
     3

If you want to go the other way, use ind2sub:

ind = sub2ind(size(A),row,col)
ind =

     7

If you want to use linear indexes and get the result [1 2 3 4 5 ...], you will have to transpose the matrix:

B = A.'
B(1:4)
B =
     1     5     9
     2     6    10
     3     7    11
     4     8    12
ans =
     1     2     3     4

The logic of ind2sub is:

Tell ind2sub how many rows and columns a matrix have, i.e. size(A). In this case 3 and 4. Then give ind2sub a linear index (which you seem to know what is). Then what it basically does is:

row = mod((ind-1), size(A,1))+1  %// size(A,1) is the number of rows
row =
     1
col = ceil(ind/size(A,1))  %// size(A,2) is the number of columns
col =
     3

To illustrate with a last example:

A = zeros(2,3);
ind = 1:numel(A);
row = mod((ind-1), size(A,1))+1 
col = ceil(ind/size(A,1))
row =
     1     2     1     2     1     2
col =
     1     1     2     2     3     3

[row col] = ind2sub(size(A),ind)
row =
     1     2     1     2     1     2
col =
     1     1     2     2     3     3
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
  • Thats it. Thanks man. The last section. Thats the one I was looking for. – Dipak Jan 19 '15 at 07:10
  • Can you please tell me the logic of the reverse? Means finding the array index using matrix position? It will be great if you explained me that too. – Dipak Jan 19 '15 at 09:11