Remove rows that contain NaN

5 vues (au cours des 30 derniers jours)
Christopher Wible
Christopher Wible le 19 Juin 2019
Commenté : Rik le 19 Juin 2019
I am currently trying to remove all rows that contain a NaN.
In other words, if you are given this input : A = [ 1 5 8; -3 NaN 14; 0 6 NaN]
The output should be: B = [1 5 8]
This is what I have so far, but I keep getting an error saying the ii index cannot exceed 1.
A = [ 1 5 8
-3 NaN 14
0 6 NaN ];
B = remove_nan_rows(A)
function B = remove_nan_rows(A)
[row,column] = size(A);
for ii = 1:row
for jj = 1:column
if isnan(A(ii,jj)) == 1
A(ii,:) = [];
end
end
end
B = A;
end

Réponses (1)

madhan ravi
madhan ravi le 19 Juin 2019
B=A;
B(any(isnan(B),2),:)=[]
  7 commentaires
Adam Danz
Adam Danz le 19 Juin 2019
Yeah, good catch. Also, there are some circumstances where you can remove an element from a matrix such as
a = 1:10;
a(2) = [];
so i'll remove that comment to avoid confusion.
Rik
Rik le 19 Juin 2019
You can also loop backwards
for n=size(A,2):-1:1

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements 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