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

问题描述 投票:0回答:1

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.

View Functions

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.

matlab function range convolution function-handle
1个回答
1
投票

The error message is pretty clear about the problem: the double operators && and || are only suitable for scalar values (they are called short-circuit operators. For vector-wise computation use their single versions & and | (so-called element-wise operators.

The difference is crucial if it comes to runtime:

With logical short-circuiting, the second operand, expr2, is evaluated only when the result is not fully determined by the first operand, expr1.

so simply change your code to

x = @(t) 2.*( ((-2 <= t) & (t <= 1)) +2).^2.*18.*((2 <= t) & (t <= 3)).*-9.*( ((4 <= t) & (t <= 5)) -5);
h = @(t) 3*((0 <= t) & (t <= 2)) -6*( ((4 <= t) & (t <=4) ) -3);

ADDED Although this was not your answer, you can get the desired plot with the following snippet

% upper level
upLvl = 17;
x_cnst = @(t) upLvl.*(t>=1 & t<3);
x_lin = @(t) (upLvl-(upLvl/2.*(t-3))).*(t>=3 & t<=5);
x_exp = @(t) upLvl/exp(3)*exp(t+2).*(t<1);
x = @(t) x_exp(t) + x_cnst(t) + x_lin(t);

h = @(t) 3.*t.*(t < 2) +(6-3.*(t-2)).*( t >= 2);

I broke the function up into the individual sections to keep a better overview. Nevertheless, I recommend to rather write a complete function with if-elseif statements than to use anonymous function handles in this case.

© www.soinside.com 2019 - 2024. All rights reserved.