I would like to plot a piecewise function that is not continuous using the following code. However, the output always appears a continuous function, as MATLAB joins the gaps between these sub-functions.
i1 = -2:0;
i2 = 0:pi/2;
i3 = pi/2:pi;
f1 = sinh(i1)+2;
f2 = sin(i2)-2;
f3= 2*i3.^2-2*pi*i3+3;
plot([i1 i2 i3],[f1,f2,f3]);
How should I resolve this problem in a not-so-complicated way?
PS. I am using MATLAB 2013a, it seems that the function piecewise doesn't exist in this version.
Add nan between the functions, that'll disjoin them:
i1 = -2:0;
i2 = 0:pi/2;
i3 = pi/2:pi;
f1 = sinh(i1)+2;
f2 = sin(i2)-2;
f3= 2*i3.^2-2*pi*i3+3;
plot([i1 nan i2 nan i3],[f1,nan,f2,nan,f3]);

The other option, resulting in the same graph, is to plot all three of them separately using hold on:
figure;
hold on
plot(i1,f1,'b');
plot(i2,f2,'b');
plot(i3,f3,'b');
Or use the plot(X,Y,X1,Y1,...,Xn,Yn syntax:
figure;
plot(i1,f1,'b',i2,f2,'b',i3,f3,'b')
Note that for the latter two you must specify the line style, so as to prevent MATLAB from making them separate colours, hence the 'b'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With