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!

댓글 수: 1

xRah
xRah 2020년 11월 26일
I included the code that I assumed to be correct

댓글을 달려면 로그인하십시오.

 채택된 답변

Ameer Hamza
Ameer Hamza 2020년 11월 26일

0 개 추천

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

댓글 수: 1

xRah
xRah 2020년 11월 26일
It seems that using the piecewise route shows the same graph as mine. I forgot to include the values of t in the code above. Thank you Hamza for the clarification. I really do appreciate it!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 11월 26일

1 개 추천

syms f(x) t
f(x) = piecewise(x<0, 0, 0 <= x & x < 2, x^2 - 1, 2 <= x & x < 5, 2*x - 3, 5 <= x, sin(x));
f(t)
ans = 
sympref('HeavisideAtOrigin', 1);
y = (t.^2-1).*[heaviside(t)-heaviside(t-2)]+(2.*t-3).*[heaviside(t-2)-heaviside(t-5)]+sin(t).*heaviside(t-5)
y = 
yp = rewrite(y, 'piecewise')
yp = 
fplot(f(t)-y, [-1 10])
The formulas come out the same except in a different order of cases, and the difference between the two appears to be all zero

댓글 수: 1

xRah
xRah 2020년 11월 26일
Hi Walter and thank you for your input.
I am not entirely sure I follow everything you did, but how come your output graph looks different from my output?

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

2020년 11월 26일

댓글:

2020년 11월 26일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by