软件 | f=@(x) 带范围 + 转换的函数句柄

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

我有这些函数,其代码旨在绘制两个信号 - x(t) 和 h(t) - 以及它们的时间范围,然后找到两个信号的卷积。

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

但是,我遇到了这个错误。

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)

我想使用函数句柄来绘制它们。 有办法解决这个问题吗?

提前感谢您的回答。

错误消息非常清楚地说明了问题:双重运算符 && and || are only suitable for scalar values (they are called short-circuit operators. For vector-wise computation use their single versions & and |(所谓的 逐元素运算符 .

如果涉及到运行时,差异是至关重要的:

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

所以只需将您的代码更改为

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 虽然这不是您的答案,但您可以使用以下代码段

获得所需的情节
% 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);

我将该功能分解为各个部分,以便更好地了解概况。尽管如此,在这种情况下,我建议宁愿使用 if-elseif 语句编写一个完整的函数,也不要使用匿名函数句柄。