remove Nan from a row vector using if statement only

조회 수: 10 (최근 30일)
swetha S
swetha S 2019년 7월 6일
댓글: madhan ravi 2019년 7월 6일
I have a row vector. Ch (1,1155). I want to remove columns that have NaN.
for k=1:122
p=1;
for m=1:1155
if( (ch(1,m) ~= NaN )
Datan(1,p)=ch(1,m);
p=p+1
end
end
end
But the above codes doesn't remove NAN
  댓글 수: 1
Rik
Rik 2019년 7월 6일
As a side note: your outer loop does not affect the rest of your code, so it is useless.

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 7월 6일
isnan() would suffice your need
doc isnan
  댓글 수: 2
Guillaume
Guillaume 2019년 7월 6일
It's more than suffice, it's necessary!
madhan ravi
madhan ravi 2019년 7월 6일
True , should have used "should" instead of "would" , thank you for the pointer :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Guillaume
Guillaume 2019년 7월 6일
But the above codes doesn't remove NAN
One important property of NaN is that NaN is never equal to anything, including NaN. Hence NaN == NaN is always false, and NaN ~= NaN is always true.So, yes your code can't work.
As others have said, you have to use isNaN to check if a number is NaN. As usual in matlab, isNaN works on matrices too, so there's no point in using a loop:
datan = ch(~isnan(ch)); %as long as ch is a vector
It's unclear what the purpose of the k loop is in a code.
Finally, if you are hell-bent on using a loop, you should never hard code the end of a loop when you're looping over the elements of a matrix/vector. Always ask matlab how many elements there are. That way if the number of elements in the matrix/vector changes, you don't have to edit your code:
for m = 1:numel(ch) %iterate over the elements of ch

Stephan
Stephan 2019년 7월 6일
편집: Stephan 2019년 7월 6일
Datan=ch(~isnan(ch));

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by