I have a matrix like this:
A = [1, 2, 3, 4, 5, NaN, NaN, NaN, NaN, NaN;
1, 2, 3, 4, 5, 6, 7, NaN, NaN, NaN;
1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I would like to know how I can count the number of values in each row excluding any NaN
s.
So I would get an output like:
output = [5;
7;
10;]
If A
is a 2D array, e.g.
A = [1, 2, 3, 4, 5, NaN, NaN, NaN, NaN, NaN;
1, 2, 3, 4, 5, 6, 7, NaN, NaN, NaN;
1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and you want to count the number of NaN
entries on each row of A
, you can simply use
>> sum(~isnan(A), 2)
ans =
5
7
10
isnan(A)
returns a logical array of the same size as A
, in which (logical1
indicates a NaN
and 0
a non-NaN
.
Note that you have to use the isnan
function, here. In particular, the expression A == ~NaN
is useless: it would simply return a logical array of the same size as A
but full of (logical) 0
's. Why? Because, according to floating-point arithmetic, NaN == NaN
always returns "false" (i.e. logical 0
, in MATLAB).
Then, by applying MATLAB's not operator (~
) to that, you get a logical array of the same size as A
, in which 1
indicates a non-NaN
and 0
a NaN
.
Finally, sum(~isnan(A), 2)
returns a column vector in which the i-th entry corresponds to the number of logical 1
's on the i-th row of ~isnan(A)
.
The resulting column vector is exactly what you want: a count, row by row, of the non-NaN
entries in A
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With