Extract lines of a three dimensional matrix using an array of indices and NO for-loop
1 回表示 (過去 30 日間)
古いコメントを表示
I have a three dimensional 10x5x2 array. Example:
r(:,:,1) = [1 0 2 1 1; 2 0 3 1 1; 3 0 4 1 1; 4 0 1 1 -1; 5 0 -1 1 1; 1 1 3 1 -1; 2 1 2 1 1; 3 1 5 0 -1; 4 1 4 1 -1; 5 1 1 0 -1];
r(:,:,2) = [1 0 2 1 -1;2 0 3 1 1;3 0 1 1 -1;4 0 1 1 -1;5 0 -1 1 1;1 1 1 1 -1;2 1 2 1 1;3 1 4 1 1;4 1 5 1 1;5 1 3 0 1]
and logical vector m like for instance: m =
10×2 logical array
1 0
0 0
0 1
0 0
0 0
0 0
0 0
0 0
0 0
0 0
how can I access those lines of r, when m(:,k) is used as index vector of r(:,:,k). In this example the result should be line 1 of r(:,:,1) and line 3 of r(:,:,2) or
1 0 2 1 1
3 0 1 1 -1
important: for performance reasons I want to do it without a for-loop.
Thanks for anyone's help!
0 件のコメント
採用された回答
BobH
2020 年 3 月 4 日
Use column 1 of m to select rows of r in the first
>> r( m(:,1), :,1)
ans =
1 0 2 1 1
Use column 2 of m to select rows of r in the other
>> r( m(:,2), :,2)
ans =
3 0 1 1 -1
3 件のコメント
BobH
2020 年 3 月 5 日
oops. commented in wrong place.
You can use arrayfun and pass in numbers which you'll use as indexes
a = arrayfun(@(X) r( m(:,X), :, X ), 1:size(r,3), 'un', 0 );
The result comes out as an array of cells, but that's easy to make usable again
b = vertcat( a{:} )
b =
1 0 2 1 1
3 0 1 1 -1
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!