Apply 2-D logical mask to obtain masked third dimension values in 3-D array
Show older comments
This is difficult to describe in words so I have given an example below. I have a 3-D array. Some of the values are NaNs (although this is not directly relevant to my question). I want to apply a 2-D mask to the first two dimensions and arrange all the third dimensions behind the mask as sequential rows in a 2-D array. I'm looking for a way to do this without 'for' loops.
Here's the example:
% Set up the example 3-D array and mask
BW = logical([0,0,1; 0,1,1; 1,1,0; 1,0,0]); %create a mask
A = 9*ones(4,3,3); % create a 3 dimensional array
A(:,:,2) = 8*ones(4,3); % Make the second 'slice' 8s
A(:,:,3) = 7*ones(4,3); % Make the third 'slice' 8s
A(1,3,1) = NaN; % add a NaN
A(3,2,3) = NaN; % add another NaN
A(4,1,2) = NaN % add another NaN
% Apply the mask and organise the masked third dimension values into a 2-D array
my2Darray = zeros(1,size(A,3));
for row=1:(size(A,1))
for col=1:(size(A,2))
if (BW(row,col))
mySpectrum = squeeze (A(row, col,:))';
my2Darray = cat (1, my2Darray, mySpectrum);
end
end
end
my2Darray(1,:) = [] % Get rid of the first row of zeros
The outcome is correct. The total number of rows in my2Darray should be equal to sum(sum(BW)).
But is there an elegant way to reshape this that doesn't require the 'for' loops, please?
Accepted Answer
More Answers (1)
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!