# How to plot different colors (scatter or line) depending on (i+1<i) or (i+1>i) condition ?

1 view (last 30 days)
C.PR on 30 Jan 2024
Commented: C.PR on 30 Jan 2024
Dear All,
I have a problem for which I don't know where to start :/
Let's say I have this
x=0:10;
y = sin(x);
I would like to have two different color for y, depending on the following condition :
• if the curve is increasing = plot in red (so not just superior to a random number but superior to the previous number)
• if the curve is decreased = plot in blue
I can imagine it would be something like :
for x=0:10
y = sin(x);
end
if sin(i+1)>sin(i)
plot(x, y, 'r')
elseif sin(i+1)>sint(i)
plot(x, y, 'b')
end
I think I understood what to do, but I have no idea where to start and how to write this correctly ..
If someone has ever done this ?
Thanks a lot

Anjaneyulu Bairi on 30 Jan 2024
Hi,
To plot the curve with different colors depending on whether the curve is increasing or decreasing, we can use the output value of the function.
Code for reference
x = 0:0.1:10; % To get a smoother curve
y = sin(x);
figure;
hold on;
for i = 2:length(x)
if y(i) > y(i-1)
% Curve is increasing, plot in red
plot(x(i-1:i), y(i-1:i), 'r');
else
% Curve is decreasing, plot in blue
plot(x(i-1:i), y(i-1:i), 'b');
end
end
xlabel('x');
ylabel('sin(x)');
title('Curve Increasing (Red) and Decreasing (Blue) Segments');
hold off;
Hope it helps to resolve your query.
C.PR on 30 Jan 2024
Wow, having a great answer in 25 minutes !
I will now adjust to my "real" data set.
(Both of you @Animesh and @Anjaneyulu Bairi replied with 1 minute difference .. thank you, I have to accept only one answer I think :/)

Animesh on 30 Jan 2024
You can iterate over the points on the curve and check the condition for whether the function is increasing or decreasing.
The first point is plotted black since there is no previous point to compare with.
% Define the range of x values
x = 0:0.1:10;
y = sin(x);
% Plot the first point
plot(x(1), y(1), 'ko'); % 'ko' plots the point in black color
hold on;
for i = 2:length(x)
% Check if the curve is increasing
if y(i) > y(i-1)
plot(x(i-1:i), y(i-1:i), 'r');
% Check if the curve is decreasing
elseif y(i) < y(i-1)
plot(x(i-1:i), y(i-1:i), 'b');
else
plot(x(i-1:i), y(i-1:i), 'k'); % Plot the segment in black
end
end
% Labels and title for clarity
xlabel('x');
ylabel('sin(x)');
hold off; % Release the hold on the current plot
You can use a smaller step size for x to get a smoother curve.
C.PR on 30 Jan 2024
Wow, having a great answer in 25 minutes !