필터 지우기
필터 지우기

Indexing Array Elements Using Row Number Stored in another Matrix

조회 수: 2 (최근 30일)
Ben
Ben 2020년 8월 26일
댓글: Ben 2020년 8월 27일
This seems like it should be a fairly simple common thing to do and Yet I cannot find any similar questions or information anywhere on the forums. Basically, all I want to do is index values in a matrix using the numbers stored in another Matix. For example if I have a Matrix A
A = [5 14 24 5; 16 12 22 15; 8 55 44 21; 3 2 34 65]
and a Matix B
B = [1; 2; 4; 3]
The numbers contained in B correspond to row numbers that need to be accessed in A. In otherwords I would like to access the values in the following locations of matrix A (1,1), (2,2), (4,3), (3,4). I would then like to store these values in a new Matrix. So in this instance, the output contained in that new Matrix would be 5 12 34 21
I tried the following:
A = [5 14 24 5; 16 12 22 15; 8 55 44 21; 3 2 34 65];
B = [1; 2; 4; 3];
for i = 1:4
z = B(1,i)
Y(i) = A(z,i)
end

채택된 답변

madhan ravi
madhan ravi 2020년 8월 26일
편집: madhan ravi 2020년 8월 26일
Wanted = A(sub2ind(size(A), B, (1:numel(B)).'))
  댓글 수: 5
Stephen23
Stephen23 2020년 8월 27일
>> A = [5,14,24,5;16,12,22,15;8,55,44,21;3,2,34,65];
>> B = [1;2;4;3]; % row subscript indices
>> C = 1:numel(B); % column subscript indices
>> X = sub2ind(size(A),B(:),C(:)); % linear indices
>> Y = A(X)
Y =
5
12
34
21
Ben
Ben 2020년 8월 27일
Thank You,
I understand this now. That works perfectly.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by