嵌套调用积分失败

时间:2017-07-12 20:22:47

标签: matlab integration integral function-handle

试试这段代码,效果很好。

a=1;b=2;
% A two-variate function 
f2= @(x,y) x+y;
derivedF2=@(x) integral(@(y) f2(x,y), a,b);
% Test the evaluation of the derived function handle
derivedF2(0);
% Test the integration of the derived function handle
% integralVal=integral(derivedF2,a,b);
% integralVal=integral(@(x) derivedF2(x),a,b);
% Test plotting of the derived function handle
figure(11);
ezplot(derivedF2);

但是如果你取消注释以integralVal开头的行。代码中断。

显然,派生的函数句柄不支持集成操作,还是我错过了什么?

1 个答案:

答案 0 :(得分:1)

简短回答:您应该添加'ArrayValued'选项:

integralVal=integral(derivedF2,a,b, 'ArrayValued', true);

<强>解释

您应该阅读错误消息:

  

函数的输出必须与输入的大小相同。如果FUN是一个数组值的被积函数,请设置&#39; ArrayValued&#39;   选项为true。

因为derivedF2是以矢量化方式计算的,即它通过提供f向量而不是单个标量来一次评估y个不同y坐标,MATLAB也无法以矢量化的方式评估外积分。因此,您应该将'ArrayValued'选项添加到外部整数,即:

integralVal=integral(derivedF2,a,b, 'ArrayValued', true);

请注意,ezplot还会生成以下相关警告:

  

警告:函数无法评估数组输入;矢量化功能可以加快其评估并避免   需要遍历数组元素。

请注意,问题纯粹与嵌套调用integral有关,以下代码也会导致同样的错误:

integralVal=integral(@(x) integral(@(y) f2(x,y), a,b),a,b);

什么是Array Valued功能?

  

...一个接受标量输入并返回向量,矩阵或N-D数组输出的函数。

因此,如果@(y) f2(x, y)是一个数组,x是一个数组值函数,即它返回一个标量输入为y的数组。

存在两种避免数组值问题的可能性:

  • 避免@(y) f2(x, y)是数组值函数,即避免x是一个数组。这可以通过指示derivedF2是如上所述的数组值函数来完成,尽管 - 严格来说 - 它不是数组值函数,即积分应该具有相同数量的输出和输入。但是,它在内部使用数组值函数,即@(x) f2(x, y)是数组值函数,因为Matlab默认以矢量化方式计算被积函数,即它使用向量y

    < / LI>
  • 告诉Matlab @(y) f2(x, y)是数组值函数

    derivedF2=@(x) integral(@(y) f2(x,y), a,b, 'ArrayValued', true);
    

    这可能是一种更直观的方法,但速度较慢,因为内部积分的调用频率远高于外部积分。

Array Valued 的替代解释是你告诉matlab不使用矢量化,但是对于这种解释,名称​​ Array Valued 有点误导。

相关问题