フィルターのクリア

How to vary color on single 2d line generated using a 'for loop' and conditional statements?

1 回表示 (過去 30 日間)
I have completed a script that runs a range of x values through for loops that generates various outputs correlated to the conditional statements and plots them. How would I allocate 3 various colors to the curve dependent on which condition was used to generate that section of the curve? Is it possible to define the color of a curve over a specific domain or x value? I have read over a question previously posted for varying color on 2d lines but was unable to duplicate it. I have included my current script below. Thank you for any insight or direction!
clc; clear all;
x=-2:.01:6;%x defined
for k=1:length(x);%for loop initiated and k defined
if x(k)<-1;%first conditional statment
y(k)=exp(x(k)+1);%resulting statement if condition1 is met
elseif (x(k)>=-1)&(x(k)<5);%2nd condition
y(k)=2+cos(pi*x(k));%resulting statement if condtion2 is met
else
y(k)=10*(x(k)-5)+1;%resulting statement if condition3 is met
end
end
plot(x,y),xlabel('Time (SECONDS)'),ylabel('Height (KM)')

採用された回答

Walter Roberson
Walter Roberson 2013 年 10 月 7 日
編集済み: Walter Roberson 2013 年 10 月 7 日
line() and lineseries() objects must be a single color for their entire length. You would need to break into distinct lines every time the color changed.
Before you break things into lines, you need to decide what portion should be colored what.
If the first two points are in the first condition, then you probably want the line segment between them to be the first color, right?
Okay, now if the third point is the second condition, then what color should be used for where? This is the segment joining point 2 (generated by condition 1) with point 3 (generated with condition 2). Should it be the color of the originating point, condition 1? Should it be the color of the destination point, condition 2? Should it switch half-way between the two from the color for condition 1 to the color to condition 2? Should the vertices be colored instead of the lines? Should the line segment colors then be determined by interpolation?
Question: for the purpose of this code, are we allowed to make the assumption that x will be strictly increasing, or could x sometimes go backwards?
  5 件のコメント
Walter Roberson
Walter Roberson 2013 年 10 月 7 日
x = linspace(....);
y = zeros(size(x));
index1 = (x < -1);
index2 = (x < 5) & (~index1);
index3 = ~(index1 | index2);
y(index1) = f1(x(index1)); %first formula
y(index2) = f2(x(index2)); %second formula
y(index3) = f3(x(index3)); %third formula
plot( x(index1), y(index1), 'r', x(index2), y(index2), 'g', x(index3), y(index3), 'b')
Jeremiah
Jeremiah 2013 年 10 月 7 日
Check Mate! Thank you

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by