Adding different colors to the same plotting line

16 visualizaciones (últimos 30 días)
Hermes Chirino
Hermes Chirino el 4 de Dic. de 2018
Editada: Adam Danz el 25 de Jun. de 2023
Hi MATLAB community, I am trying to add different colors to the same plot line. I want a color for 0<x<100, another color for 100<x<150, and another color for 150<x<200. Here is my code:
clear
clc
dx = 200/1000;
x = 0:dx:200;
for k = 1:length(x)
if x(k) <= 100
y(k) = sqrt(x(k));
end
if x(k) >100 && x(k)<=150
y(k) = (2*x(k))-190;
end
if x(k) > 150
y(k)=110;
end
end
plot(x,y,'color',rand(1,3),'DisplayName', '\surd(x)')
legend('-DynamicLegend')
hold all
plot(x,y,'color',rand(1,3),'DisplayName', '2x')
plot(x,y,'color',rand(1,3),'DisplayName', 'Constant')
xlabel('x'), ylabel('y')

Respuesta aceptada

Adam Danz
Adam Danz el 4 de Dic. de 2018
Editada: Adam Danz el 25 de Jun. de 2023
The variables idx1, idx2, idx3 replace your for-loop and mark the indices of x and y that are categorized by your logical expressions. You can use them to calculate Y and to plot the 3 portions of the line with different colors.
clear
clc
dx = 200/1000;
x = 0:dx:200;
idx1 = x <= 100;
idx2 = x > 100 & x <= 150;
idx3 = x > 150;
y = nan(size(x));
y(idx1) = sqrt(x(idx1));
y(idx2) = (2.*x(idx2))-190;
y(idx3) = 110;
plot(x(idx1),y(idx1),'color',rand(1,3),'DisplayName', '\surd(x)')
legend('-DynamicLegend','Location','NorthWest')
hold all
plot(x(idx2),y(idx2),'color',rand(1,3),'DisplayName', '2x')
plot(x(idx3),y(idx3),'color',rand(1,3),'DisplayName', 'Constant')
xlabel('x'), ylabel('y')

Más respuestas (0)

Categorías

Más información sobre Labels and Styling en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by