Effacer les filtres
Effacer les filtres

I get index error, but the correct result. How can I avoid this?

2 vues (au cours des 30 derniers jours)
Alicia Cuber Caballero
Alicia Cuber Caballero le 1 Août 2019
Commenté : KALYAN ACHARJYA le 1 Août 2019
I am trying to solve this Cody problem where I need to remove all rows that contain NaN-s.
My code looks like this:
[m,n]=size(A)
b = abs(sum(A'))
b1=length(b)
if n==1
iter2 = 0
for l=1:m
if isnan(A(l,:))==1
A(l,:)=[]
B=A
elseif isnan(A(l))==0
end
end
elseif n>1
iter1 = 0
for i=1:b1
if isnan(b(i))==1
elseif isnan(b(i))==0
iter1 = iter1+1
B(iter1,:) = A(i,:)
end
end
end
where, in the overarching if, the if part works for column matrices, and the elseif for any other matrices. (I know there are probably better ways to solve it, but I'm trying to figure them out on my own).
It works. However, I get the alert that in
if isnan(A(l,:))==1
"Index exceeds the number of array elements (4)" for the column vector A = [ 1 3 6 NaN 3 NaN]'. I am assuming it is becauyse for l=5, I still get a four element vector. However, the result is correct, and if it weren't for that error message, I believe the Cody problem would accept my answer.
Thanks in advance!

Réponse acceptée

KALYAN ACHARJYA
KALYAN ACHARJYA le 1 Août 2019
Modifié(e) : KALYAN ACHARJYA le 1 Août 2019
"I am trying to solve this Cody problem where I need to remove all rows that contain NaN-s".
A =[1 3 6 NaN 3 NaN]'
idx=find(isnan(A));
A(idx,:)=[]
Result:
A =
1
3
6
3
  2 commentaires
madhan ravi
madhan ravi le 1 Août 2019
find() can be omitted here
KALYAN ACHARJYA
KALYAN ACHARJYA le 1 Août 2019
Agreed @Madhan
A(isnan(A),:)=[]
I am sure you have more simpler one.
Thanks Always

Connectez-vous pour commenter.

Plus de réponses (1)

Alicia Cuber Caballero
Alicia Cuber Caballero le 1 Août 2019
Thank you! That's a simpler solution :)

Catégories

En savoir plus sur Matrix Indexing 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