Adding different colors to the same plotting line

15 ビュー (過去 30 日間)
Hermes Chirino
Hermes Chirino 2018 年 12 月 4 日
編集済み: Adam Danz 2023 年 6 月 25 日
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')

採用された回答

Adam Danz
Adam Danz 2018 年 12 月 4 日
編集済み: Adam Danz 2023 年 6 月 25 日
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')
  2 件のコメント
Hermes Chirino
Hermes Chirino 2018 年 12 月 4 日
great, it worked, thanks Adam.
Adam Danz
Adam Danz 2018 年 12 月 4 日
Great!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLabels and Styling についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by