Indexing matrices with matrices in MATLAB
I am trying to pull values from a matrix that serves mainly as a lookup table. For this I have a row coordinate matrix and a column coordinate matrix. Is there a way that I can output the values like this:
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 to
A(R, C) = 1, 5 1, 5
or
A(R(:), C(:)) =
1
1
5
5
What actually happens when you run these commands, you get every permutation of the matrix. So, in my example, you end up with a 4x4 result 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 on each index matrix / vector so that the result shows
A(1,1) A(2,1) A(1,1) A(2,1)
Thank!
source to share
Indeed, you are pointing out a subtle issue with Matlab indexing.
To solve this problem, you need to convert rows columns indexes R
, C
in the linear indices . One easy way to do this is 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 working hard at runtime and want to avoid overhead sub2ind
, you can convert the indices directly:
A( size(A,1)*(C-1)+R )
source to share