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

조회 수: 2 (최근 30일)
VIJENDRA
VIJENDRA 2015년 4월 22일
댓글: VIJENDRA 2015년 4월 23일
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