Reputation: 341
I have a simple plot as below
I would like to select the signal between 50 to 100 and change the color to red. Here is the code that I wrote
close all
clear all
clc
%%
t=1:200 ;
y=sin(t);
figure (1), hold on, plot(t, y);
[x1,y1] = ginput(2)
figure(2), hold on, plot(t,y,'b'), plot(t(t>=x1(1)), y(t(t>=x1(1))),
'r',t(t<=x1(2)), y(t(t<=x1(2))),'b')
but what I receive is logically not correct
I wanted to change the color of samples between 50 to 100 into red. Could you please let me know how I can do it? (I examined
t(x1(1)<t<x1(2))
but it did not work.
Upvotes: 2
Views: 182
Reputation: 22314
Note that y(t(t>=x1(1))
happens to be valid in this case because t=1:200
corresponds to the indices of y
.
To solve your problem you just need to find the proper values using logical indexing.
t=1:200;
y=sin(t);
figure (1), hold on, plot(t, y);
[x1,y1] = ginput(2);
dt = t(2)-t(1);
figure(2), hold on;
rng1 = t < x1(1);
rng2 = (t+dt) >= x1(1) & (t-dt) <= x1(2);
rng3 = t > x1(2);
plot(t(rng1), y(rng1), 'b');
plot(t(rng2), y(rng2), 'r');
plot(t(rng3), y(rng3), 'b');
Edit I realized I potentially left gaps in the plot. Extended the inequalities to correct this.
Upvotes: 4