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

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

KSSV
KSSV am 1 Jun. 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

Weitere Antworten (1)

LO
LO am 1 Jun. 2021
Bearbeitet: LO am 1 Jun. 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 Kommentare
LO
LO am 1 Jun. 2021
Bearbeitet: LO am 1 Jun. 2021
the 3, in true (1,3)
is K+1.
if your K is 4, use true(1,5)
Yared Daniel
Yared Daniel am 1 Jun. 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]

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by