BMG
BMG

Reputation: 87

Plotting piecewise functions. Change colors?

I am plotting a piecewise function, and I was wondering if it was possible to change the color of the line for each portion of the function? For instance, have it yellow, red and green.

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);

Upvotes: 1

Views: 738

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

If you want different colors you need to plot each portion separately.

The most flexible way to do that is to define the portion limits, compute an index that tells which portion each x belongs too (ind in the code below), and plot separately according to the value of that index:

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

enter image description here

If you want to specify the line type or color of each portion, define a cell array of strings and use a different string in each call to 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

Upvotes: 4

Related Questions