how to write an if statement for a matrix with some NaN elements?
이전 댓글 표시
Hello all,
I have a matrix with some elements 0s or 1s and the rest are NaNs. I would like to write an if statement that ignores the NaN elements of the matrix. I have tried
if (a(:)==1 or a(:)==0)
------------
end
however, I am getting an error. I would appreciate if somebody can help me please. Thanks.
댓글 수: 7
I'm not sure I understand the question, but you might be able to use conditionals in your variable like
if all(a(a~=NaN))
% All nonNaN a's are not zero
% Do Something
elseif ~any(a(a~=NaN))
% No nonNaN a's are not zero
% Do Something
else
%Mixed Bag case
%Dp something
end
Mnr
2015년 5월 5일
Matthew
2015년 5월 5일
Mrn,
You might want to reconsider your if statement, right now your conditional doesn't return a single boolean, but an array of them, and only the first value in the array is considered. You'll recieve more helpful help if you clarify exactly what behavior you are looking for.
That said, you can do things like the following which seem to be along the lines you're looking for.
A = [1,2,NaN;4,NaN,6;NaN,8,9];
AnotNaN = ~isnan(A)
AnotNaN =
1 1 0
1 0 1
0 1 1
A(AnotNaN)
ans =
1
4
2
8
6
9
A(~AnotNaN) = -100
A =
1 2 -100
4 -100 6
-100 8 9
Walter Roberson
2015년 5월 5일
Note that direct comparisons of a value to NaN by using == will always fail, even for NaN values. (NaN == NaN) is false. The way to test for NaN is with isnan() .
Mnr
2015년 5월 6일
As Walter Roberson pointed out, it is very important to know that NaN is never equal to anything, not even itself:
>> NaN==NaN
ans =
0
The only way to test for NaN is using isnan, (or by implication isinf and isfinite):
Walter Roberson
2015년 5월 6일
~(A==A) is also a test for A being NaN.
답변 (1개)
Walter Roberson
2015년 5월 5일
nonnanlocs = ~isnan(a);
a(nonnanlocs) = SomeFunction(a(nonnanlocs));
카테고리
도움말 센터 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!