Remove items from 3D Matrix with 2D mask for each timestep

Hi,
I would like to mask a 3D matrix (A) using a 2D Mask-Matrix containing several NaN's (B). The mask should be applied for each 3rd Dimension step (here: timestep) of A. I have a loop solution based on a 2D approach, but would rather like to use a logical approach.
Can someone recommend a logical approach?
Matrices are for example:
% data
A(:,:,1) = [1 2
2 4]
A(:,:,2) = [5 2
2 3]
B_mask(:,:) = [1 2
NaN 1]
% the loop solution based on 2D
for i=1:2
AA=A(:,:,i)
AA(isnan(B_mask)) = nan;
A(:,:,i)=AA;
end
% solution
A(:,:,1) = [1 2
NaN 4]
A(:,:,2) = [5 2
NaN 3]

 Accepted Answer

% data
A(:,:,1) = [1 2
2 4] ;
A(:,:,2) = [5 2
2 3] ;
B = [1 2
NaN 1] ;
B_mask = repmat(isnan(B),1,2) ;
A(B_mask) = NaN
A =
A(:,:,1) = 1 2 NaN 4 A(:,:,2) = 5 2 NaN 3

More Answers (0)

Tags

Asked:

on 11 Mar 2021

Commented:

on 11 Mar 2021

Community Treasure Hunt

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

Start Hunting!