3
votes

I'm trying to pull values from a matrix that is serving essentially as a look up table. To do this I have a matrix of row coordinates and a matrix of column coordinates. Is there a way that I can pull the values as follows:

A(R, C)

or

A(R(:), C(:))

For example:

A = [ 1, 2, 3, 4; 
      5, 6, 7, 8; 
      9, 0, 1, 2; 
      3, 4, 5, 6 ];

R = [ 1, 2; 
      1 2];
C = [ 1, 1; 
      1 1];

I would like to find some command so that

A(R, C) =

1, 5
1, 5

or

A(R(:), C(:)) =

1
1
5
5

What actually happens when you do these commands is you get every permutation of the matrix. So in my example, you get a resultant 4x4 matrix consisting of

A(1,1)  A(1,1)  A(1,1)  A(1,1)
A(1,1)  A(1,1)  A(1,1)  A(1,1)
A(2,1)  A(2,1)  A(2,1)  A(2,1)
A(2,1)  A(2,1)  A(2,1)  A(2,1)

Is there a way to just do the indexing pair-wise down each index matrix/vector so the result shows

A(1,1)  A(2,1)
A(1,1)  A(2,1)

Thanks!

2

2 Answers

4
votes

Indeed, you are pointing to a delicate issue with Matlab indexing.
To solve this issue, you need to convert the row-col indices R, C to linear indices. One simple way to do so is using sub2ind:

 A( sub2ind( size(A), R, C ) );

Here's how it works

>> A(sub2ind(size(A),R,C))
ans =
 1     5
 1     5

>> A(sub2ind(size(A),R(:),C(:)))
ans =
 1
 1
 5
 5

If you are tight on runtime and want to avoid the overhead of sub2ind you can convert the indices directly yourself:

 A( size(A,1)*(C-1)+R )
1
votes

You can use arrayfun

>> arrayfun(@(x,y) A(x,y), R, C)
ans =
     1     5
     1     5

You get the result in the same size as R and C not as a vector.