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)')
0 个评论
采纳的回答
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
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')
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!