How to remove all volumes that only have zeros in them from a 5D array?

3 次查看(过去 30 天)
So I need to work with a 5 dimensional array and I am not sure if I understand them correctly.
The size of the 5D array is
size(Results)
ans =
2 10 112 240 30
Now I want to check for every 3D array with the size 112x240x30 if it contains only zeros and remove those "empty" arrays.
My comprehension goes only as far as 3D arrays maybe 4D arrays. If Results was a 3D array and I searched for empty pages, I would do something like this
Results = Results(:,:,any(Results~=0,[1 2]));
So I guess for searching empty 3D arrays in a 4D array would be like this
Results = Results(:,:,:,any(Results~=0, [1 2 3]));
But transfering this to a 5D array would only search for all-zero 4D arrays or am I wrong?
Hope I described my problem well enough, thanks in advance!

回答(1 个)

Jan
Jan 2023-3-1
Start with using loops at first:
data = randi([0, 1], [2, 10, 112, 240, 30]); % Some test data
for i3 = 1:size(data, 3)
for i4 = 1:size(data, 4)
for i5 = 1:size(data, 5)
if ~any(data(:, :, i3, i4, i5))
% mark this submatrix for deleting
% (by the way: do not delete inside the loop, because this
% would shift the following indices!)
end
end
end
end
Now imagine, only the first submatrix contains only zeros: i3=1, i4=1, i5=1, and you want to delete this submatrix. Then the output array cannot have a rectangular shape anymore. This would be like a matrix, whose first row have one element less than the others.
So in the general case the wanted procedure is not possible.
Before you struggle with the smart and efficient vectorized solutions, writing dull loops is a good strategy to check, if 1. the procedure is working at all and 2. if the loop or the vectorized code is faster finally. Starting with smart optimized code is called "premature optimization" and a wide-spread programming anti-pattern.
  3 个评论
Jan
Jan 2023-3-1
You can create a {112x240x30} cell array, which contains 2x10 double matrices as elements. Then you can replaces such matrices by empty arrays. Another option is to create a [112x240x30] logical array, which is true for unique (or repeated) 2x10 matrices. This would be easy: any(data, [1,2]).
lit
lit 2023-3-2
编辑:lit 2023-3-2
I thought of another solution. The all-zero arrays originate from a continue statement in a for loop. So instead I assign the non-zero arrays to where the all-zero arrays would be
But thank you anyways

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by