对积分的嵌套调用失败

Nested call to integral fails

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

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 开头的行。代码中断。

看来派生函数句柄不支持积分运算,还是我漏了什么?

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

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

说明

您应该阅读您的错误消息:

Output of the function must be the same size as the input. If FUN is an array-valued integrand, set the 'ArrayValued' option to true.

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

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

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

Warning: Function failed to evaluate on array inputs; vectorizing the function may speed up its evaluation and avoid the need to loop over array elements.

请注意,问题完全与对 integral 的嵌套调用有关,以下代码也会导致相同的错误:

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

什么是 Array Valued 函数?

... a function that accepts a scalar input and returns a vector, matrix, or N-D array output.

所以,如果 x 是一个数组,@(y) f2(x, y) 是一个数组值函数,即它 returns 一个数组,用于 y.[=35 的标量输入=]

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

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

  • 告诉 Matlab @(y) f2(x, y) 是数组值函数:

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

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

Array Valued 的另一种解释是,您告诉 matlab 不要使用矢量化,但对于这种解释,名称 Array Valued 是有点误导。