Extract 2D array from 3D array using logical index

30 ビュー (過去 30 日間)
Leo Pio D'Adderio
Leo Pio D'Adderio 2024 年 10 月 31 日 11:36
編集済み: Stephen23 2024 年 10 月 31 日 14:31
I have a PxMxN array that I want to convert in a PxK 2D array. K has to be obtained from a logical matrix MxN. Consequently, numel(K)<=numel(MxN). Can anyone help me? Thanks.

回答 (1 件)

Stephen23
Stephen23 2024 年 10 月 31 日 14:14
編集済み: Stephen23 2024 年 10 月 31 日 14:31
"I have a PxMxN array that I want to convert in a PxK 2D array. K has to be obtained from a logical matrix MxN. Consequently, numel(K)<=numel(MxN). Can anyone help me?"
Just use the indexing and then RESHAPE (which does not move any data in memory so is very efficient):
format compact
A = randi(9,5,4,3)
A =
A(:,:,1) = 8 1 6 4 4 5 5 3 3 8 4 7 3 3 6 4 6 1 8 7 A(:,:,2) = 6 3 4 5 1 5 9 7 6 8 8 1 2 4 3 9 6 9 7 7 A(:,:,3) = 2 4 8 7 9 5 1 9 9 4 1 4 5 5 9 8 3 7 2 2
X = randi(0:1,4,3);
X = logical(X)
X = 4x3 logical array
0 1 1 0 0 0 1 1 0 0 1 0
B = A(:,X); % easy indexing
B = reshape(B,size(A,1),[])
B = 5×5
6 6 4 5 2 5 1 9 7 9 4 6 8 1 9 6 2 3 9 5 8 6 7 7 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Checking the first of the index values:
[R,C] = find(X,1,'first')
R = 3
C = 1
A(:,R,C)
ans = 5×1
6 5 4 6 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
This works because MATLAB applies the final index to all trailing dimensions:
An interesting side-effect of this is that linear indexing is really just subscript indexing with one index.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by