在 matlab 中集成一个调用另一个函数的函数



我正在使用 integral2 matlab 命令对双积分进行数值计算。我的代码如下:

l1=0; m1=0; 
funn =  @(theta,phi)(Y_hsph_new(l1,m1,theta,phi));
q = integral2(funn,0,pi/2,0,2*pi);

其中"Y_hsph_new"是我自己设计的MatLab函数,写成:

function [ YYY ] = Y_hsph_new(l1,m1,theta,phi)
% OUTPUT: (I x (N+1)^2) matrix
I = length(theta);
Y=zeros(I,(l1+1)^2);
for i=1:I
k=1;
for n=0:l1
P=legendre(n,2*cos(theta(i))-1); % (2*x-1) for transformation
for m=-n:n   % degree
if m>0
Y(i,k)=(sqrt(((2*n+1)*factorial(n-abs(m)))/((2*pi)*factorial(n+abs(m)))))*P(abs(m)+1)*sqrt(2)*cos(m*phi(i));
elseif m == 0
Y(i,k)=(sqrt(((2*n+1)*factorial(n))/((2*pi)*factorial(n))))*P(1);
else
Y(i,k)=(sqrt(((2*n+1)*factorial(n-abs(m)))/((2*pi)*factorial(n+abs(m)))))*P(abs(m)+1)*sqrt(2)*sin(abs(m)*phi(i));
end
k=k+1;
end
end
end
YYY = Y(:,m1+l1+1+(l1)^2);

我已经在其他常用代码中使用了Y_hsph_new函数,并且工作正常。我相信也许功能代码很好,但是与将在集成中使用的配置相关的内容会导致问题。我在运行时遇到的错误是:-

Error using integral2Calc>integral2t/tensor (line 241)
Integrand output size does not match the input size.
Error in integral2Calc>integral2t (line 55)
[Qsub,esub] = tensor(thetaL,thetaR,phiB,phiT);
Error in integral2Calc (line 9)
[q,errbnd] = integral2t(fun,xmin,xmax,ymin,ymax,optionstruct);
Error in integral2 (line 106)
Q = integral2Calc(fun,xmin,xmax,yminfun,ymaxfun,opstruct);

经过多次尝试,我正在认真地拔头发。如果有人能在这方面帮助我,那将非常有帮助。谢谢。

定义funn的方式与 integral2 不一致。例如,如果我输入一个 theta 和 phi 值的数组来funn我希望输出相同的数组大小,但这不是funn产生的。例如:

[th ph]=meshgrid(linspace(0,pi/2),linspace(0,2*pi))
>> size(th)
ans =
100   100

而:

>> size(funn(th,ph))
ans =
100     1

因此,funn无法正常工作,无法在 integral2 中使用。 我认为在你的函数中开始的第一个地方是I = length(theta);行,因为如果 theta 是 2d 数组,则 theta 的长度不合适。

最新更新