Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of non-NaN values in each row of a 2D array

Tags:

nan

matlab

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 NaNs. So I would get an output like:

output = [5;
          7;
          10;]
like image 726
user3644826 Avatar asked Feb 11 '23 03:02

user3644826


1 Answers

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

Breakdown

  1. 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).

  2. 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.

  3. 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.

like image 165
jub0bs Avatar answered Feb 28 '23 01:02

jub0bs