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

조회 수: 2 (최근 30일)
Yared Daniel
Yared Daniel 2021년 6월 1일
댓글: Yared Daniel 2021년 6월 1일
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

채택된 답변

KSSV
KSSV 2021년 6월 1일
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

추가 답변 (1개)

LO
LO 2021년 6월 1일
편집: LO 2021년 6월 1일
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
LO
LO 2021년 6월 1일
편집: LO 2021년 6월 1일
the 3, in true (1,3)
is K+1.
if your K is 4, use true(1,5)
Yared Daniel
Yared Daniel 2021년 6월 1일
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]

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by