keep element greater than immediate previous element
Show older comments
Hi,
x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ]; I want to keep one vector whereby the next element is greater than the immediate previous element. keep = [[1 2 3 4 6 8 8.5 9 11 12 ]; to discard if the element is smaller than or equal to the immediate previous element. discard = [3 2 3 4 5 5 6] (the bold elements in x).
I am using loop to do that and I didn't get what I want. could help modify my code or advise any alternative way? thanks in advance!
clc; clear; close all
x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ];
m = length(x);
k=1; n = 1; i =1; j=2;
while i < m-1 & j < m
if x(j) >= x(i)
keep(n) = x(j);
n=n+1;
i=i+1;
j=j+1;
elseif x(j) < x(i)
discard(k) = x(j);
k = k+1;
i=i;
j=j+1;
end
end
Accepted Answer
More Answers (1)
per isakson
on 24 May 2020
An alternative
%%
x = [1 2 3 4 3 2 3 4 6 8 5 5 6 8.5 9 11 12 ];
%%
dx = 1;
while not( isempty( dx ) )
dx = find((diff(x)<=0));
x(dx+1)=[];
end
disp( x )
output
Columns 1 through 5
1 2 3 4 6
Columns 6 through 10
8 8.5 9 11 12
>>
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!