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

조회 수: 408 (최근 30일)
Jason Baxter
Jason Baxter 2012년 8월 7일
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

채택된 답변

Daniel Shub
Daniel Shub 2012년 8월 7일
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
Jason Baxter
Jason Baxter 2012년 8월 7일
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

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Oleg Komarov
Oleg Komarov 2012년 8월 7일
[minval,idx] = min(sum(isnan(a)))

Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 7일
편집: Azzi Abdelmalek 2012년 8월 7일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by