How to plot different colors (scatter or line) depending on (i+1<i) or (i+1>i) condition ?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
C.PR
el 30 de En. de 2024
Comentada: C.PR
el 30 de En. de 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
0 comentarios
Respuesta aceptada
Anjaneyulu Bairi
el 30 de En. de 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.
Más respuestas (1)
Animesh
el 30 de En. de 2024
Hi @C.PR
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.
Ver también
Categorías
Más información sobre Scatter Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!