how to select an element from each row in a matrix given a vector of column indeces per row (no for loops)

51 ビュー (過去 30 日間)
Hello, I saw posts to similar questions, but I still couldn't figure out how to do what I want to do. I have a matrix and a vector of values. This vector contains the column indeces to the element I want to extract from each row. for ex:
A=[1 2 3; 3 5 6; 7 8 9];
b = [2 ;1; 1];
I tried x=A(:,b), but this returns
x=A(:,b)
x =
2 1 1
5 3 3
8 7 7
But what I was hoping to get was
x= [2;3;7].
I could do it with a for loop, but is there a different/direct way of doing this?
Thank you, Jorge

採用された回答

jonas
jonas 2018 年 7 月 17 日
編集済み: jonas 2018 年 7 月 17 日
If you want one value from each row, then you could use sub2ind, like this:
A(sub2ind(size(A),1:size(A,1),b'))
This is useful if you have vectors of subscripts (i.e. rows and columns) and you want to extract the corresponding values from a matrix. In this case you want one value per row, so the 2nd argument is just [1 2 3].
  2 件のコメント
Andy
Andy 2023 年 12 月 6 日
what if there are multiple columns to extract ... A(sub2ind(size(A),1:size(A,1),b')) becomes a complete mess:
A(sub2ind(size(A),repmat(1:size(A,1),1,nrColumns),b'(:)))
Having a matrix MxN, where we need to extract 5 elements from each line, on random column IDs ... isn't there a more elegant than a FOR solution?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by