Indexing Array Elements Using Row Number Stored in another Matrix

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 日

0 投票

Wanted = A(sub2ind(size(A), B, (1:numel(B)).'))

5 件のコメント

Ben
Ben 2020 年 8 月 26 日
Doesn't seem to work. I get the following error
A =
5 14 24 5
16 12 22 15
8 55 44 21
3 2 34 65
B =
1
2
4
3
Error using sub2ind (line 51)
The subscript vectors must all be of the same size.
Error in Untitled (line 35)
Wanted = A(sub2ind(size(A), B, 1:numel(B)))
madhan ravi
madhan ravi 2020 年 8 月 26 日
Please try the answer properly before commenting.
Ben
Ben 2020 年 8 月 26 日
Perhaps you could kindly elaborate slightly on you answer above. It's not completely clear to me from that one line how this code works. you are saying that linear indices for the row and column subscripts need to be extracted.
If you could elaborate slightly it would be appreciated.
Ben
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 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

Ben
2020 年 8 月 26 日

コメント済み:

Ben
2020 年 8 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by