绘制分段函数。改变颜色?
Plotting piecewise functions. Change colors?
我正在绘制一个分段函数,我想知道是否可以更改函数每个部分的线条颜色?
例如,黄色、红色和绿色。
x = -10: 0.01: 10;
for k = 1 : length(x)
if x(k) < -1
y(k) = x(k)+2;
elseif -1<=x(k) && x(k)<= 2
y(k) = x(k).^2;
else
y(k) = -2*x(k)+8;
end
end
plot(x, y);
如果你想要不同的颜色,你需要分别绘制每个部分。
最灵活的方法是定义部分限制,计算一个索引,告诉每个 x
属于哪个部分(下面代码中的 ind
),并根据单独绘制到该索引的值:
limits = [-1 2];
ind = sum(bsxfun(@ge, x(:).', limits(:)),1); %'// how many values in limits are exceeded or
% // equalled by each x. Indicates portion
hold on %// or hold all in old Matlab versions
for n = 0:numel(limits)
plot(x(ind==n), y(ind==n)) %// plot portion
end
如果要指定每个部分的线条类型或颜色,请定义一个字符串元胞数组,并在每次调用 plot
时使用不同的字符串:
limits = [-1 2];
linespec = {'r-','b:','g-.'}; %// should contain 1+numel(limits) elements
ind = sum(bsxfun(@ge, x(:).', limits(:)),1); %'
hold on
for n = 0:numel(limits)
plot(x(ind==n), y(ind==n), linespec{n+1})
end
我正在绘制一个分段函数,我想知道是否可以更改函数每个部分的线条颜色? 例如,黄色、红色和绿色。
x = -10: 0.01: 10;
for k = 1 : length(x)
if x(k) < -1
y(k) = x(k)+2;
elseif -1<=x(k) && x(k)<= 2
y(k) = x(k).^2;
else
y(k) = -2*x(k)+8;
end
end
plot(x, y);
如果你想要不同的颜色,你需要分别绘制每个部分。
最灵活的方法是定义部分限制,计算一个索引,告诉每个 x
属于哪个部分(下面代码中的 ind
),并根据单独绘制到该索引的值:
limits = [-1 2];
ind = sum(bsxfun(@ge, x(:).', limits(:)),1); %'// how many values in limits are exceeded or
% // equalled by each x. Indicates portion
hold on %// or hold all in old Matlab versions
for n = 0:numel(limits)
plot(x(ind==n), y(ind==n)) %// plot portion
end
如果要指定每个部分的线条类型或颜色,请定义一个字符串元胞数组,并在每次调用 plot
时使用不同的字符串:
limits = [-1 2];
linespec = {'r-','b:','g-.'}; %// should contain 1+numel(limits) elements
ind = sum(bsxfun(@ge, x(:).', limits(:)),1); %'
hold on
for n = 0:numel(limits)
plot(x(ind==n), y(ind==n), linespec{n+1})
end