How do I count the number of NaNs in a Vector?

466 views (last 30 days)
I have an nxm array a(n,m) with an unknown number of NaNs inside. I want to look for the column a(i,:) which contains the least number of Nans, how do I do this?
thank you for your help

Accepted Answer

Daniel Shub
Daniel Shub on 7 Aug 2012
This is a straight forward question and given you haven't shown any attempt to solve it, I am hesitant to provide an answer ...
Start by making some nonsense data
n = 10;
m = 5;
a = randn(n, m);
a(rand(numel(a), 1) < 0.25) = nan;
a =
0.5377 -1.3499 0.6715 0.8884 NaN
1.8339 3.0349 -1.2075 -1.1471 NaN
-2.2588 0.7254 0.7172 -1.0689 0.3192
NaN -0.0631 NaN -0.8095 0.3129
NaN 0.7147 0.4889 -2.9443 -0.8649
-1.3077 -0.2050 1.0347 1.4384 NaN
-0.4336 -0.1241 NaN 0.3252 -0.1649
0.3426 NaN -0.3034 -0.7549 0.6277
3.5784 NaN 0.2939 1.3703 NaN
NaN 1.4172 -0.7873 -1.7115 1.1093
The ISNAN function tells you if an element is a nan (1) or not (0).
isnan(a)
ans =
0 0 0 0 1
0 0 0 0 1
0 0 0 0 0
1 0 1 0 0
1 0 0 0 0
0 0 0 0 1
0 0 1 0 0
0 1 0 0 0
0 1 0 0 1
1 0 0 0 0
Now we want to sum up all the ones in each column. We have the SUM function that does that
sum(isnan(a))
ans =
3 2 2 0 4
To get the final answer we want to find which column has the smallest sum. The MIN function usually returns the smallest values, but if you read the documentation, the second output argument is the index of the minimum value.
[~, col] = min(sum(isnan(a)))
col =
4
where the ~ notation allows for the first output argument to be ignored.
  1 Comment
Jason Baxter
Jason Baxter on 7 Aug 2012
sorry, I haven't attempted it because I had no idea how to answer it, i'm not very good at Matlab yet. Thank you Daniel for your answer, I will answer more questions than I ask to keep the community going when I have time. Thank you for your answer! Jason

Sign in to comment.

More Answers (2)

Oleg Komarov
Oleg Komarov on 7 Aug 2012
[minval,idx] = min(sum(isnan(a)))

Azzi Abdelmalek
Azzi Abdelmalek on 7 Aug 2012
Edited: Azzi Abdelmalek on 7 Aug 2012
s=sum(isnan(a)); %
[dd,ff]=min(s);
find(s==dd) % gives the rows that contain the least "nan"
% it's possible there are many rows containing the least nan

Products

Community Treasure Hunt

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

Start Hunting!