MATLAB: Piecewise to Heaviside problem

heavisideMATLABpiecewise

Hi all,
Trying to create a plot using heaviside function after being given a piecewise function. The code, I managed to get 2 different results, so I am not sure which is correct.
The piecewise function is the following:
x^2 – 1; if 0 <= x < 2
f(x) = 2x – 3; if 2 <= x < 5
sin(x); if x >= 5
My code is the following.
y = (t.^2-1).*[heaviside(t)-heaviside(t-2)]+(2.*t-3).*[heaviside(t-2)-heaviside(t-5)]+sin(t).*heaviside(t-5);
plot(t,y)
I may have made a mistake in the conversion to heaviside, and I am not so well versed in the step function, so it's a little challenging to analyze the graph to see whether or not it is correct. Any input is greatly appreciated!

Best Answer

Yes, your code is correct. Following will work
t = 0:0.01:10;
y = (t.^2-1).*[heaviside(t)-heaviside(t-2)]+(2.*t-3).*[heaviside(t-2)-heaviside(t-5)]+sin(t).*heaviside(t-5);
plot(t,y)
However, an easier solution is to use piecewise()
syms x
f(x) = piecewise(0<=x<2, x^2-1, 2<=x<5, 2*x-3, 5<=x, sin(x));
fplot(f, [0 10])
Related Question