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

1 vue (au cours des 30 derniers jours)
Yared Daniel
Yared Daniel le 1 Juin 2021
Commenté : Yared Daniel le 1 Juin 2021
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

Réponse acceptée

KSSV
KSSV le 1 Juin 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

Plus de réponses (1)

LO
LO le 1 Juin 2021
Modifié(e) : LO le 1 Juin 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 commentaires
LO
LO le 1 Juin 2021
Modifié(e) : LO le 1 Juin 2021
the 3, in true (1,3)
is K+1.
if your K is 4, use true(1,5)
Yared Daniel
Yared Daniel le 1 Juin 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]

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by