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

3 views (last 30 days)
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

Accepted Answer

KSSV
KSSV on 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

More Answers (1)

LO
LO on 1 Jun 2021
Edited: LO on 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 Comments
LO
LO on 1 Jun 2021
Edited: LO on 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 on 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]

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!