在 MATLAB 中使用 Integral2 函数时出错

Errors when using the Integral2 function in MATLAB

据我所知,没有人问过这个问题。 我被要求计算一个函数的二重积分,以及相同的二重积分,但交换积分的顺序(即:首先积分 dydx,然后积分 dxdy)。这是我的代码:

    %Define function to be integrated
f = @(x,y) y^2*cos(x);

    %First case. Integration order: dydx
ymin = @(x) cos(x);
I = integral2(f,ymin,1,0,2*pi)

    %Second case. Integration order: dxdy
xmin = @(y) asin(y)+2*pi/2;
xmax = @(y) asin(y)-pi/2;
B = integral2(f,xmin,xmax,-1,1)

我得到的错误是:

Error using integral2 (line 71)

XMIN must be a floating point scalar.

Error in EngMathsA1Q1c (line 5)

I = integral2(f,ymin,1,0,2*pi)

我确定我的错误很简单,但我以前从未使用过 Integral2,所以我找不到答案。谢谢。

该错误指出您不能为积分限制传入一个函数。您需要为每个积分极限指定一个标量值。此外,函数的 dimensions/operations 中存在一些错误。试试这个:

%Define function to be integrated
f = @(x,y) y.^2.*cos(x);%changed to .^ and .* 

%First case. Integration order: dydx
%ymin = @(x) cos(x);
I = integral2(f,-1,1,0,2*pi)%use scalar values for limits of integration

%Second case. Integration order: dxdy
%xmin = @(y) asin(y)+2*pi/2;
%xmax = @(y) asin(y)-pi/2;
B = integral2(f,0,2*pi,-1,1)% same issue, must use scalars

根据 integral2 documentation,变量限制作为第二对限制给出。所以你的第一个积分应该是

%    Define function to be integrated
f = @(x,y) y.^2.*cos(x);

%    First case. Integration order: dydx
ymin = @(x) cos(x);
I = integral2(f,0,2*pi,ymin,1);

常量极限集总是先行, Matlab 假设 f 的第一个参数与第一组极限相关联,而 [=2] 的第二个参数=16=] 与第二组限制相关联,这可能是第一个参数的函数。


我指出第二部分是因为如果你想切换积分顺序,你还需要相应地切换 f 输入的顺序。考虑以下示例:

fun = @(x,y) 1./( sqrt(2*x + y) .* (1 + 2*x + y).^2 )

一个漂亮的小函数,其参数不对称(即 fun(x,y) ~= fun(y,x))。让我们在第一象限中的一个细长三角形上对其进行积分,顶点位于 (0,0)、(2,0) 和 (0,1)。然后与 dA == dy dx 积分,我们有

>> format('long');
>> ymax = @(x) 1 - x/2;
>> q = integral2(fun,0,2,0,ymax)
q =
   0.220241017339352

酷。现在让我们整合 dA == dx dy:

>> xmax = @(y) 2*(1-y);
>> q = integral2(fun,0,1,0,xmax)
q =
   0.241956050772765

糟糕,第一次计算不等于!这是因为 fun 被定义为 x 作为第一个参数, y 作为第二个参数,但是之前对 integral2 的调用暗示 y 是第一个fun 的参数,它具有 01 的常数限制。我们如何解决这个问题?只需定义一个翻转参数的新函数:

>> fun2 = @(y,x) fun(x,y);
>> q = integral2(fun2,0,1,0,xmax)
q =
   0.220241017706984

世界上一切都很好。 (虽然您可能会注意到由于 integral2 的误差容限,两个正确答案之间存在细微差异,可以根据文档通过选项进行调整。)