how to write an if statement for a matrix with some NaN elements?
Afficher commentaires plus anciens
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
Mnr
le 5 Mai 2015
Matthew
le 5 Mai 2015
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
le 5 Mai 2015
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
le 6 Mai 2015
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
le 6 Mai 2015
~(A==A) is also a test for A being NaN.
Réponses (1)
Walter Roberson
le 5 Mai 2015
nonnanlocs = ~isnan(a);
a(nonnanlocs) = SomeFunction(a(nonnanlocs));
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!