How to extract values from a matrix using a row - column matrix?

I have a matrix like
A =
0.2180 0.5714 0.2476 0.3942 0.9253 0.5082
0.3906 0.5881 0.6529 0.3806 0.3819 0.7947
0.3381 0.0287 0.0652 0.3696 0.3735 0.1351
0.7459 0.0911 0.0163 0.7531 0.3298 0.2050
0.3690 0.5010 0.5201 0.6119 0.9038 0.1902
0.4232 0.9183 0.6523 0.2392 0.4661 0.0019
and a matrix having row and column indices
loc =
1 2
2 5
4 3
6 6
I want the extract the values of locations (1,2), (2,5), (4,3) and (6,6) from matrix A when I do this
val = A(loc(:,1),loc(:,2));
it gives me
val =
0.5714 0.9253 0.2476 0.5082
0.5881 0.3819 0.6529 0.7947
0.0911 0.3298 0.0163 0.2050
0.9183 0.4661 0.6523 0.0019
I can use diag(val); to get the locations values but is there any way so that i could get values directly without getting that square matirx
val =
0.5714
0.3819
0.0163
0.0019

 Accepted Answer

Yes! You can use sub2ind to achieve this:
A = [...
0.2180 0.5714 0.2476 0.3942 0.9253 0.5082
0.3906 0.5881 0.6529 0.3806 0.3819 0.7947
0.3381 0.0287 0.0652 0.3696 0.3735 0.1351
0.7459 0.0911 0.0163 0.7531 0.3298 0.2050
0.3690 0.5010 0.5201 0.6119 0.9038 0.1902
0.4232 0.9183 0.6523 0.2392 0.4661 0.0019];
loc = [...
1 2
2 5
4 3
6 6];
X = sub2ind(size(A), loc(:,1), loc(:,2));
and then run this in the command window:
>> A(X)
ans =
0.5714
0.3819
0.0163
0.0019

More Answers (1)

[nRows nCols ] = size(A);
A(nRows*(loc(2)-1)+loc(1))

1 Comment

This is what sub2ind does and I'd recommend using it as it works regardless of the number of dimensions of A.

Sign in to comment.

Asked:

on 22 Apr 2015

Commented:

on 23 Apr 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!