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

1 visualizzazione (ultimi 30 giorni)
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
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!

Risposte (1)

Jan il 1 Mar 2023
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!)
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 Commenti
lit il 2 Mar 2023
Modificato: lit il 2 Mar 2023
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

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by