Move all NaN to end of matrix columns.

8 vues (au cours des 30 derniers jours)
Hampus Alfredsson
Hampus Alfredsson le 5 Mar 2018
Commenté : Jorge Morales le 28 Jan 2020
Hi!
I have a 3D matrix of many rows. At som places there is NaN values in the middle of some rows that I don't want there, ex:
A(:,:,1) = [8 8; 9 9; 8 8; 9 9; NaN NaN; 1 1; 2 2; 3 3; 5 5; 7 7];
A(:,:,2) = [2 2; 3 3; 4 4; NaN NaN; NaN NaN; 1 2; 2 5; 3 7; 5 6; 7 8];
I want to remove the NaN's somehow. But since it is a 3D matrix it has to remain the same size and hence I can't just remove all NaN's by setting A(any(any(isnan(A),3),2),:,:) = [].

Réponse acceptée

Stephen23
Stephen23 le 5 Mar 2018
Modifié(e) : Stephen23 le 5 Mar 2018
Without sorting the other values:
>> A(:,:,1) = [8 8; 9 9; 8 8; 9 9; NaN NaN; 1 1; 2 2; 3 3; 5 5; 7 7];
>> A(:,:,2) = [2 2; 3 3; 4 4; NaN NaN; NaN NaN; 1 2; 2 5; 3 7; 5 6; 7 8];
>> [~,idr] = sort(isnan(A),1);
>> S = size(A);
>> [~,id2,id3] = ndgrid(1:S(1),1:S(2),1:S(3));
>> idx = sub2ind(S,idr,id2,id3);
>> B = A(idx)
B(:,:,1) =
8 8
9 9
8 8
9 9
1 1
2 2
3 3
5 5
7 7
NaN NaN
B(:,:,2) =
2 2
3 3
4 4
1 2
2 5
3 7
5 6
7 8
NaN NaN
NaN NaN
  4 commentaires
Stephen23
Stephen23 le 5 Déc 2018
@Bryan: if you like it then you can give it a vote :)
Jorge Morales
Jorge Morales le 28 Jan 2020
How can you apply this to a Table??

Connectez-vous pour commenter.

Plus de réponses (2)

M
M le 5 Mar 2018
if you want to move all NaN to end of matrix you can use:
sort(A)
ans(:,:,1) =
1 1
2 2
3 3
5 5
7 7
8 8
8 8
9 9
9 9
NaN NaN
ans(:,:,2) =
1 2
2 2
2 3
3 4
3 5
4 6
5 7
7 8
NaN NaN
NaN NaN
  1 commentaire
Hampus Alfredsson
Hampus Alfredsson le 5 Mar 2018
Yes. But I want all the other rows to remain in the same order.

Connectez-vous pour commenter.


Jos (10584)
Jos (10584) le 6 Mar 2018
10+ years ago, I submitted the function sortlind to the Matlab File Exchange, which returns linear indices (rather than sub indices as sort does). This is how it works:
[~, I] = sortlind(isnan(A)) ;
B = A(I) ; % all NaNs of A moved to the end

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by