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

4 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2015-4-22
编辑:Stephen23 2015-4-22
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

更多回答(1 个)

Punit
Punit 2015-4-22
[nRows nCols ] = size(A);
A(nRows*(loc(2)-1)+loc(1))
  1 个评论
Guillaume
Guillaume 2015-4-22
This is what sub2ind does and I'd recommend using it as it works regardless of the number of dimensions of A.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by