Effacer les filtres
Effacer les filtres

Remove zeros from a 3D array

30 vues (au cours des 30 derniers jours)
Uerm
Uerm le 3 Fév 2020
Commenté : Uerm le 10 Fév 2020
Hi,
I have a 3D array A = 90x38021x1633. The second dimension (38021) contains a lot of zeros as I have done zero padding before concatenating multiple 3D arrays to get A. How can I now remove these zeros such that B = 90xYx1633, where Y < 38021?
Thanks!

Réponse acceptée

the cyclist
the cyclist le 3 Fév 2020
Modifié(e) : the cyclist le 3 Fév 2020
Do you mean you have "slices" of all zeros? Then this should work:
% Create an array like your A matrix, where some "slices" of data is all zeros
A = repmat([0 0 0 0; 1 0 0 0; 1 0 1 0],[1 1 5]);
% Find indices to slices in the 1-3 plane that have any non-zeros.
idx = any(A ~= 0,[1 3]);
% Create B from only the slices that have non-zeros
B = A(:,idx,:);
Just use your A, instead of the pretend one I made. Also, you can combine the two steps by just doing
B = A(:,any(A ~= 0,[1 3]),:);
but I wanted to call out explicitly what is going on.

Plus de réponses (1)

Nils Speetzen
Nils Speetzen le 3 Fév 2020
Hi,
I assume you want to remove rows/planes containing only zeros. To find these, you can use
all(A==0, [1 3])
This searches for all planes where all entries along the first and third dimension are equal to zero.
To remove all those rows/planes, you can directly index A via this expression:
A(:,all(A==0, [1 3]),:) = []
I hope this helps!
  8 commentaires
the cyclist
the cyclist le 3 Fév 2020
I'm not certain I fully understand, but I am getting some idea. Again, looking at just some small arrays as examples.
So maybe you had an array A1:
A1 = [1 2 0;
3 4 5];
where that zero was added for padding.
And you have another array A2:
A2 = [5 6 7;
8 9 0];
where that zero was also added for padding.
And you end up with A by concatenating A1 and A2 along the third dimension:
A = cat(3,A1,A2)
A(:,:,1) =
1 2 0
3 4 5
A(:,:,2) =
5 6 7
8 9 0
So A has some data where the zeros are not meaningful, and are just placeholders.
But, repeating my prior comment, you CANNOT just "remove" them. A matrix cannot have an "empty" spot.
You could do
A(A==0) = NaN
A(:,:,1) =
1 2 NaN
3 4 5
A(:,:,2) =
5 6 7
8 9 NaN
which replaces the zeros with NaN (not-a-number). You might then be able to do later steps in your calculation. Does that help?
Uerm
Uerm le 10 Fév 2020
Thanks a lot for your help! It makes sense now.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by