Effacer les filtres
Effacer les filtres

replacing element which are <= previous element with NaN

3 vues (au cours des 30 derniers jours)
HYZ
HYZ le 3 Juin 2020
Modifié(e) : Rik le 3 Juin 2020
Hi,
I have a vector x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ]; I want to replace any element which are less than or equal to previous number with NaN.
Want = [1 2 3 4 NaN NaN NaN NaN 6 8 NaN NaN NaN 8.5 9 11 12 ];
My current code gave Want = [1 2 3 4 NaN NaN NaN NaN 6 8 5 5 6 8.5 9 11 12 ]; the code didn't work for later part. Could anyone please advise? Thanks in advance!
n = 1; i =1; j=2;
while i < m-1 & j < m
if x(j) > x(i)
want(n) = x(j);
n=n+1;
i=i+1;
j=j+1;
elseif x(j) <= x(i)
want(n) = NaN;
n=n+1;
i=i;
j=j+1;
end
end

Réponse acceptée

Rik
Rik le 3 Juin 2020
Modifié(e) : Rik le 3 Juin 2020
This code may not be efficient for very large vectors.
x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ];
y=movmax(x,[numel(x) 0]);
y([false diff(y)<=0])=NaN;
You can also use a for-loop, since you know the number of iterations beforehand:
x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ];
current_max=x(1);
for n=2:numel(x)
if x(n)<=current_max
x(n)=NaN;
else
current_max=x(n);
end
end
disp(x)

Plus de réponses (0)

Catégories

En savoir plus sur NaNs 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