用两种不同的颜色给同一条线着色

Color the same line using two different colors

我必须绘制一个线性函数并以所有负值都是红色而正值是蓝色的方式为其着色。

这只是我想问的一个例子。

一般化,是否可以用与函数其余部分不同的颜色为函数的特定区间着色,而不必绘制不同的图?

没有。为负值创建一个红色图,使用 hold on,然后为正值创建一个蓝色图。

x = [-10:0.1:10].'; %//range
x1 = x(x<=0); %//negative values and zero
x2 = x(x>=0); %//positive values and zero
figure; %//open figure
hold on %// plot things in the same figure
plot(x1,x1,'r') %//plot negative values
plot(x2,x2,'b') %//plot positive values