- Technical Services and Consulting
- Embedded Systems | Firmware Developement | Simulations
- Electrical and Electronics Engineering
Apply 2-D logical mask to obtain masked third dimension values in 3-D array
15 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Hassaan
2024-6-13
编辑:Hassaan
2024-6-13
% Define the 2D mask and 3D array with NaNs
BW = logical([0,0,1; 0,1,1; 1,1,0; 1,0,0]);
A = 9*ones(4,3,3);
A(:,:,2) = 8*ones(4,3); A(:,:,3) = 7*ones(4,3);
A(1,3,1) = NaN; A(3,2,3) = NaN; A(4,1,2) = NaN;
% Process the array
B = reshape(pagetranspose(A), [], size(A,3)); % Transpose and reshape to 2D array
mask = BW'; % Transpose the mask to match reshaped array
mask = mask(:); % Convert mask to a column vector
B(~mask, :) = []; % Apply the mask to filter the array
% Store the result in my2Darray
my2Darray = B;
% Display the final 2D array
disp(my2Darray);
------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
Professional Interests
Feel free to contact me.
3 个评论
Hassaan
2024-6-14
编辑:Hassaan
2024-6-14
@Steve Francis I used a slightly different approach didn't meant to plagiarise it. Anyhow a good solution on your end.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!