Apply logical mask to every matrix in array

212 ビュー (過去 30 日間)
Marcel345614
Marcel345614 2022 年 2 月 24 日
回答済み: Loïc Reymond 2023 年 5 月 29 日
I have a 3D array of size 640x640x20 i.e. 20 matrices of size 640x640. In addition I have a logical mask of size 640x640. How can I apply this mask to every matrix in the array? Is this only possible with a for loop?
for jj=1:20
mat_temp=B(:,:,jj);
mat_temp(mask==1)=NaN
B(:,:,jj)=mat_temp;
end
%% I tried the following but it didn't worked (mask was only applied to first matrix)
B(mask==1)=NaN;

回答 (3 件)

Jan
Jan 2022 年 2 月 24 日
編集済み: Jan 2022 年 2 月 25 日
B = reshape(1:24, 2,3,4);
mask = logical([1,0,1; 0,1,0]);
sB = size(B);
B = reshape(B, [], sB(3)); % Join the first two dimensions
B(mask, :) = NaN;
B = reshape(B, sB)
D =
D(:,:,1) = NaN 3 NaN 2 NaN 6 D(:,:,2) = NaN 9 NaN 8 NaN 12 D(:,:,3) = NaN 15 NaN 14 NaN 18 D(:,:,4) = NaN 21 NaN 20 NaN 24
% Alternatively:
M = ones(size(mask));
M(mask) = NaN;
B = B .* M;
Note: No need to compare mask with 1: mask==1. Use mask directly, if it is a logical array.
  2 件のコメント
Jan
Jan 2022 年 2 月 25 日
A speed coparison with R2018b:
X = rand(640, 640, 20);
mask = rand(640, 640) > 0.6;
rep = 1e2;
B = X;
tic;
for k = 1:rep
for jj=1:20
mat_temp = B(:,:,jj);
mat_temp(mask==1) = NaN;
B(:,:,jj) = mat_temp;
end
end
toc % Elapsed time is 8.416893 seconds.
B = X;
tic;
for k = 1:rep
sB = size(B);
B = reshape(B, [], sB(3));
B(mask, :) = NaN;
B = reshape(B, sB);
end
toc % Elapsed time is 0.966218 seconds.
B = X;
tic;
for k = 1:rep
M = ones(size(mask));
M(mask) = NaN;
B = B .* M;
end
toc % Elapsed time is 1.173872 seconds.
B = X;
tic;
for k = 1:rep
s = size(B);
f = find(mask==1) + (0:s(3)-1) .* (s(1)*s(2));
B(f) = nan;
end
toc % Elapsed time is 2.992846 seconds.
Marcel345614
Marcel345614 2022 年 2 月 25 日
Thank you! This was helpful!

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


David Hill
David Hill 2022 年 2 月 24 日
s=size(B);
f=find(mask==1)+(0:s(3)-1).*(s(1)*s(2));
B(f)=nan;

Loïc Reymond
Loïc Reymond 2023 年 5 月 29 日
The most compact way would probably be:
bsxfun(@(x,y) x.*y,mat,mask)
Or alternatively (probably slower):
mat.*repmat(mask,1,1,size(mat,3))
Where mat is your 640x640x20 matrix and mask your masking array.

カテゴリ

Help Center および File ExchangeAuthor Block Masks についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by