How can I set x-variable cutoffs using a script to include or exclude points

1 view (last 30 days)
Hi there! I'm somewhat new to using MATLAB and wanted to know what commands would help me create a script like this:
I have a set of 5 data points that look like this:
x = [40 ; 43 ; 50; 52; 60]
y = [12 ; 15 ; 20; 21; 26]
I want to create a script that I can apply to any set of data such that if the difference between consecutive x-values is less than 3, only keep the data point that has a larger y-value. On the other hand, if the consecutive x-values are greater than or equal to 3, keep both points as part of the data set. I tried using a for loop and an if statement to create a script that looks like this but am unsure what should go after the difference function to keep both data points included. Likewise, how should I format the code after the else statement to account for the scenario in which the consecutive x-value difference is less than 3 and should only keep the data point with the higher y-value?
for ii = x
if diff(x)>=3
......
else
.......
end
Thanks

Answers (1)

Rub Ron
Rub Ron on 29 Jul 2020
x = [40 ; 42; 43 ; 50; 52; 60; 70; 71 ; 73; 80];
y = [12 ; 3; 5 ; 20; 21; 26; 3; 10; 1; 15];
xy = [x y];
v = [0; diff(x)<3]';
idSt=strfind([0,v==1],[0,1])-1;
idEn=strfind([v==1,0],[1,0]);
for k=1:numel(idSt)
temp = xy(idSt(k):idEn(k),:);
[~,idMax] = max(temp(:,2));
xy(idSt(k):idEn(k),:)=repmat(temp(idMax,:),size(temp,1),1);
end
x = xy(:,1);
y = xy(:,2);
Input:
xy =
40 12
42 3
43 5
50 20
52 21
60 26
70 3
71 10
73 1
80 15
output;
xy =
40 12
40 12
40 12
52 21
52 21
60 26
71 10
71 10
71 10
80 15
  4 Comments
Isa Samad
Isa Samad on 29 Jul 2020
Edited: Isa Samad on 29 Jul 2020
In those cases, where delta x is less than 3, the highest y-value should be kept. So in the two instances you mentioned, (42, 3) should be removed since it does not satisfy delta x>=3 with respect to (40,12). Since we exclude (42,3), (43, 5) should be kept given it satisifies delta x>=3 when compared to (40,12). For the bottom data set, only (71,10) should be kept since it has the higher y-value compared to (70,3). (73,1) should be excluded since it does not satisfy the requirement of delta x >=3 when compared to (71,10).
Rub Ron
Rub Ron on 29 Jul 2020
then, the procedure is different. Thy this.
x = [40 ; 42; 43 ; 50; 52; 60; 70; 71 ; 73; 80];
y = [12 ; 3; 5 ; 20; 21; 26; 3; 10; 1; 15];
xy = [x y];
watchVar = 1;
while watchVar
for k= 2:size(xy,1)
if xy(k,1)-xy(k-1,1)<3
[~,idMax] = max(xy(k-1:k,2));
xy(k+1-idMax,:)=[];
break;
end
end
watchVar = ~(k==size(xy,1));
end
x = xy(:,1);
y = xy(:,2);
input:
xy =
40 12
42 3
43 5
50 20
52 21
60 26
70 3
71 10
73 1
80 15
output:
xy =
40 12
43 5
52 21
60 26
71 10
80 15

Sign in to comment.

Categories

Find more on Elementary Math 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!