How to remove more than K consecutive NaN values from row matrix

3 visualizaciones (últimos 30 días)
I have a row vector like this:
x=[2 5 NaN NaN 8 11 5 9 12 NaN NaN NaN NaN NaN NaN 4 2 NaN NaN 16 NaN NaN NaN 1 NaN 6 NaN NaN NaN NaN NaN NaN]
and let say k=2
So, I want to remove if consecutive NaN is more than 2, so the output for the above row matrix have to be like this:
x_new = [2 5 NaN NaN 8 11 5 9 12 4 2 NaN NaN 16 1 NaN 6]
Thank you for the help in advance

Respuesta aceptada

KSSV
KSSV el 1 de Jun. de 2021
x=[2 5 NaN NaN 8 11 5 9 12 NaN NaN NaN NaN NaN NaN 4 2 NaN NaN 16 NaN NaN NaN 1 NaN 6 NaN NaN NaN NaN NaN NaN] ;
idx = isnan(x) ;
idr = diff(find([1 diff(idx) 1]));
D = mat2cell(x',idr,size(x,1));
% Remove more than two NaN's
for i = 1:length(D)
if any(isnan(D{i})) && length(D{i})>2
D{i} = [] ;
end
end
iwant = cell2mat(D)'
iwant = 1×17
2 5 NaN NaN 8 11 5 9 12 4 2 NaN NaN 16 1 NaN 6

Más respuestas (1)

LO
LO el 1 de Jun. de 2021
Editada: LO el 1 de Jun. de 2021
K=2;
x = [1,2,3,4,NaN,NaN,NaN,7,8,9] ;
indexes=strfind(isnan(x), true(1,K+1));
x(indexes)=[];
(edited according to the comment below)
  3 comentarios
LO
LO el 1 de Jun. de 2021
Editada: LO el 1 de Jun. de 2021
the 3, in true (1,3)
is K+1.
if your K is 4, use true(1,5)
Yared Daniel
Yared Daniel el 1 de Jun. de 2021
clear
close all
clc
K=2;
x=[2 5 NaN NaN 8 11 5 9 12 NaN NaN NaN NaN NaN NaN 4 2 NaN NaN 16 NaN NaN NaN 1 NaN 6 NaN NaN NaN NaN NaN NaN] ;
indexes=strfind(isnan(x), true(1,K+1));
x(indexes)=[];
I got the followiing out put
[2 5 NaN NaN 8 11 5 9 12 NaN NaN 4 2 NaN NaN 16 NaN NaN 1 NaN 6 NaN NaN], But it would be:
[2 5 NaN NaN 8 11 5 9 12 4 2 NaN NaN 16 1 NaN 6]

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by