Borrar filtros
Borrar filtros

How can I replace NaN elements with the nearest value in the same column?

11 visualizaciones (últimos 30 días)
I am trying to replace NaN's in a vector field with the nearest value.
% I have:
M=
NaN 12
18 14
NaN NaN
NaN NaN
NaN 16
12 NaN
12 NaN
NaN 12
16 NaN
%I desire:
M=
18 12
18 14
12 16
12 16
12 16
12 12
12 12
16 12
16 12
Any information will be helpful. Thank you
  2 comentarios
AstroGuy1984
AstroGuy1984 el 25 de Abr. de 2017
Editada: AstroGuy1984 el 25 de Abr. de 2017
What do you mean by "nearest"? Do you mean "next good value"? Because that's what you appear to desire. For example the second NaN in column 1 is closer to 18 than 12.
sal135
sal135 el 26 de Abr. de 2017
I would like to have the first value of NaN to have the value of the next good value. However if the last value in the column is a NaN I would like for it to have the value of the previous good value

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 25 de Abr. de 2017
Editada: Andrei Bobrov el 26 de Abr. de 2017
FIXED 2
m = flipud(M)
t = ~isnan(m);
ii = cumsum(t);
ii(ii == 0) = 1;
ii = bsxfun(@plus,[0,ii(end,1:end-1)],ii);
m1 = m(t);
out = flipud(m1(ii))
  6 comentarios
Andrei Bobrov
Andrei Bobrov el 26 de Abr. de 2017
>> m = flipud(M);
t = ~isnan(m);
ii = cumsum(t);
ii(ii == 0) = 1;
ii = bsxfun(@plus,[0,ii(end,1:end-1)],ii);
m1 = m(t);
out = flipud(m1(ii))
out =
18 12
18 14
12 16
12 16
12 16
12 12
12 12
16 12
16 12
>>
sal135
sal135 el 26 de Abr. de 2017
Editada: sal135 el 27 de Abr. de 2017
Thank you for your help! This worked out great.

Iniciar sesión para comentar.

Más respuestas (1)

dpb
dpb el 25 de Abr. de 2017

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by