Find all values in an array neighbored on both sides by NaN.

I have an array that looks like this:
A = [1 2 4 2 NaN 2 4 NaN 6 NaN NaN 9 5 NaN];
I would like to find all values in A that have a NaN immediately adjacent on both sides. In the example above, the only value that meets this criteria is the 6. I can do it in a loop like this:
ind = false(size(A));
for n = 2:length(A)-1
if isnan(A(n-1)) && isnan(A(n+1))
ind(n)=true;
end
end
Is there a more elegant way to do this?

 Respuesta aceptada

A = [1 2 4 2 NaN 2 4 NaN 6 NaN NaN 9 5 NaN];
A(conv(double(isnan(A)),[1 0 1],'same')==2)

2 comentarios

Sean de Wolski
Sean de Wolski el 24 de Sept. de 2014
Editada: Sean de Wolski el 24 de Sept. de 2014
Note, the for-loop is plenty elegant. It could be made more elegant by calling isnan once and then indexing into it on each iteration.
idx = isnan(A)
n = numel(A);
for ii = 1:n-2
if idx(ii) && idx(ii+2)
A(ii+1)
end
end
Convolution, of course! Thanks Sean.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Identification en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 24 de Sept. de 2014

Comentada:

el 24 de Sept. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by