Row/column-wise logical indexing

9 ビュー (過去 30 日間)
Angshuman Deb
Angshuman Deb 2019 年 6 月 5 日
コメント済み: Angshuman Deb 2019 年 6 月 6 日
I have a matrix
A=[1 2 3;
4 5 6;
7 8 9];
where each row represents a group of numbers. I have a logical matrix
L = [ 0 0 0 1 1 1 1 1 1;
1 1 1 0 0 0 1 1 1;
1 1 1 1 1 1 0 0 0]
where each column represents the groups of A I want to extract.
For example,
A(L(:,1),:) gives me
[4 5 6;
7 8 9]
A(L(:,4),:) gives me
[1 2 3;
7 8 9]
Is there a way to extract all such pairs of rows of A in one vectorized step instead of looping over the columns of L?

回答 (1 件)

Akira Agata
Akira Agata 2019 年 6 月 6 日
How about the following solution?
B = arrayfun(@(k) A(L(:,k),:), 1:size(L,2), 'UniformOutput', false);
Then, your can obtain cell array B where B{1} = A(L(:,1),:), B{2} = A(L(:,2),:), ... B{9} = A(L(:,9),:).
  1 件のコメント
Angshuman Deb
Angshuman Deb 2019 年 6 月 6 日
Thanks for the answer. But I am not sure if using arrayfun is going to speed up the calculations. Because I want to use this for a matrix L with very large size along the 2nd dimension which is why I was thinking of avoiding to loop over it.

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

カテゴリ

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

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by