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 commentaires

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
Thanks, but unfortunately the above doesn't work with me. I actually have something like a=[1 ;0;NaN ;NaN] (bu with higher dimensions) I would like to only consider the elements that are not NaN. How I can do it?
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
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() .
Thanks Matthew!
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):
~(A==A) is also a test for A being NaN.

Connectez-vous pour commenter.

Réponses (1)

Question posée :

Mnr
le 5 Mai 2015

Modifié(e) :

le 6 Mai 2015

Community Treasure Hunt

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

Start Hunting!

Translated by