【问题标题】:MATLAB | f=@(x) function handle with range + convMATLAB | f=@(x) 函数句柄,范围 + conv
【发布时间】:2020-08-16 15:44:24
【问题描述】:

我有这些函数,其代码旨在绘制两个信号 - 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)

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

提前感谢您的回答。

【问题讨论】:

  • 使用 &amp; 而不是 &amp;&amp; 用于元素方面的 and

标签: matlab function range convolution function-handle


【解决方案1】:

错误消息非常清楚地说明了这个问题:双运算符 &amp;&amp; and || 仅适用于标量值(它们被称为短路运算符。对于向量计算,请使用它们的单个版本&amp; and |(所谓的元素操作符

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

通过逻辑短路,第二个操作数 expr2 仅在结果未完全由第一个操作数 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);

添加虽然这不是您的答案,但您可以使用以下 sn-p 获得所需的情节

% 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 语句编写一个完整的函数,也不要在这种情况下使用匿名函数句柄。

【讨论】:

  • 我仍然没有得到我期望的形状。是不是因为我写错了函数?函数预期图:i.stack.imgur.com/TyhqY.png
  • 效果很好!非常感谢马克斯 :)
猜你喜欢
  • 1970-01-01
  • 2018-10-30
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多