Delete certain entries in a 3D matrix

6 ビュー (過去 30 日間)
Douglas Chiang
Douglas Chiang 2020 年 4 月 8 日
編集済み: Andrei Bobrov 2020 年 4 月 9 日
OK, so I have a 4 page 3x30 3D matrix (which is 3x30x4) and would like to delete certain entries in matrix. These entries are the same on all 4 pages and the entries are stored in a 1x30 matrix like:
idx = [1 1 3 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2]
such that each entry in idx corresponses to the entry needed to be delete in each column. By say delete, I mean assigning a [ ] to the entry. To further illustrate let's say I have a 3D matrix A and idx:
A(:,:,1) = [1 2 3;
4 5 6;
7 8 9]
A(:,:,2) = [10 11 12;
13 14 15;
16 17 18]
A(:,:,3) = [19 20 21;
22 23 24;
25 26 27]
idx = [3 2 2]
I would like to get a 2x3x3 matrix B in this context:
B(:,:,1) = [1 2 3;
4 8 9]
B(:,:,2) = [10 11 12;
13 17 18]
B(:,:,3) = [19 20 21;
25 23 24]
Are there any methods that can do this without a loop?

採用された回答

Andrei Bobrov
Andrei Bobrov 2020 年 4 月 8 日
編集済み: Andrei Bobrov 2020 年 4 月 9 日
A = randi(200,3,30,4);% Let A - our array [3 x 30 x 4]
idx = [1,1,3,3,3,3,3,3,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2]';
[m,n,k] = size(A);
[i,j] = ndgrid(1:n,1:k);
A(sub2ind([m,n,k],repmat(idx(:),1,k),i,j)) = [];
B = reshape(A,m-1,n,[]);
  1 件のコメント
Douglas Chiang
Douglas Chiang 2020 年 4 月 8 日
Thanks Andrei, this is exactly what I want :)

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

その他の回答 (1 件)

Rik
Rik 2020 年 4 月 8 日
I'm assuming the last page of your example is incorrect.
clear A
A(:,:,1) = [1 2 3;
4 5 6;
7 8 9];
A(:,:,2) = [10 11 12;
13 14 15;
16 17 18];
A(:,:,3) = [19 20 21;
22 23 24;
25 26 27];
idx = [3 2 2];
sz=size(A);
rowsub=repmat(idx,1,sz(3));
colsub=repmat(1:sz(2),1,sz(3));
pagesub=repelem(1:sz(3),1,sz(2));
ind=sub2ind(sz,rowsub,colsub,pagesub);
B=A;
B(ind)=[];
szB=sz-[1 0 0];
B=reshape(B,szB)
  1 件のコメント
Douglas Chiang
Douglas Chiang 2020 年 4 月 8 日
Thanks for your answer :)

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

カテゴリ

Help Center および File ExchangeElementary Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by