f=@(x) function handle with range + conv

14 ビュー (過去 30 日間)
Aqeel Mohamed
Aqeel Mohamed 2020 年 5 月 2 日
編集済み: Aqeel Mohamed 2020 年 5 月 2 日
Dear all,
I have these functions with the code that aims to plot the two signals - x(t) and h(t) - alongside their time range then find the convolution of the two signals.
x=@(t) 2.*((-2<=t&&t<=1)+2).^2.*18.*(2<=t&&t<=3).*-9.*((4<=t&&t<=5)-5);
tx=-2:0.01:5;
h=@(t) 3*(0<=t&&t<=2) -6*((4<=t&&t<=4)-3);
th=0:0.01:4;
c=conv(x(tx),h(th));
tc=(tx(1)+th(1)):0.01:(tx(end)+th(end));
figure(1)
subplot(3,1,1); plot(tx,x(tx));
subplot(3,1,2); plot(th,h(th));
subplot(3,1,3); plot(tc,c);
However, I got this error.
Operands to the || and && operators must be convertible to logical scalar values.
Error in @(t)2.*((-2<=t&&t<=1)+2).^2.*18.*(2<=t&&t<=3).*-9.*((4<=t&&t<=5)-5)
I want to use function handle to plot them.
Is there a way to fix this problem?
Thanks in advance for your answers.

採用された回答

Deepak Gupta
Deepak Gupta 2020 年 5 月 2 日
Hi Aqeel,
Piecewise function is very helpful in writing conditional functions. Check it out:
As i see multiple errors in your code so providing a piece of code for your reference to solve this problem.
x = @(t) piecewise(t<-2, 0, -2<=t<1, 2*(t+2)^2, 1<=t<3, 18, 3<=t<5, -9*(t-5), t>5, 0);
h = @(t) piecewise(t<0, 0, 0<=t<2, 3*(t+2), 2<=t<4, -6*(t-3), t>4, 0);
tx=-2:0.01:5;
th=0:0.01:4;
xVec = double(subs(x, tx));
hVec = double(subs(h, th));
c = conv(xVec, hVec);
tc = (tx(1)+th(1)):0.01:(tx(end)+th(end));
figure(1)
subplot(3,1,1); plot(tx,xVec);
subplot(3,1,2); plot(th,hVec);
subplot(3,1,3); plot(tc,c);
Cheers.
  2 件のコメント
Deepak Gupta
Deepak Gupta 2020 年 5 月 2 日
編集済み: Deepak Gupta 2020 年 5 月 2 日
Extra Note: As your function x is not defined at tx = 5 and h at th = 4, hence matlab returns function values NaN at these time instants. To me it seems like a problem with the question. Because of this you don't see convolution plot from -2 to 9 as expected.
Aqeel Mohamed
Aqeel Mohamed 2020 年 5 月 2 日
編集済み: Aqeel Mohamed 2020 年 5 月 2 日
NIce idea, works great!
Though it won't work to those whom MATLAB version is before 2016.
I noticed the extra note, yeah the question has a mistake.
Thank you very much Deepak :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSubplots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by