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

413 visualizaciones (últimos 30 días)
Jason Baxter
Jason Baxter el 7 de Ag. de 2012
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

Respuesta aceptada

Daniel Shub
Daniel Shub el 7 de Ag. de 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 comentario
Jason Baxter
Jason Baxter el 7 de Ag. de 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

Iniciar sesión para comentar.

Más respuestas (2)

Oleg Komarov
Oleg Komarov el 7 de Ag. de 2012
[minval,idx] = min(sum(isnan(a)))

Azzi Abdelmalek
Azzi Abdelmalek el 7 de Ag. de 2012
Editada: Azzi Abdelmalek el 7 de Ag. de 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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by