在 Matlab 中嵌套调用 integral 和 integral2
Nested calls to integral and integral2 in Matlab
我这里有一些代码说明了我想在 matlab 中执行的一些积分的嵌套性质。当我 运行 以下代码时,我得到错误
Error using .*
Matrix dimensions must agree.
Error in fun1/integrand (line 7)
f = x.^2.*t;
我现在设置的方式似乎不允许 integral
函数的矢量化输出。我该怎么做才能使我的代码 运行?我在下面评论了我希望函数执行的操作。
我的代码如下:
%主要脚本:
z = linspace(0,10,10);
I = zeros(10,1);
for i = 1:10
I(i) = fun2(z(i));
end
%函数 1 在单独的文件中:
function I = fun1(x)
I = integral(@integrand,-1,1);
function f = integrand(t)
f = x.^2.*t;
end
end
%函数 2 在单独的文件中:
function I = fun2(z)
I = integral2(@integrand,-1,1,-1,1);
function f = integrand(x,y)
f = z.*fun1(x).*y; // here fun1 should return the value for all x that is swept through by integral2 during its call.
end
end
您的代码存在问题,您正在组合使用 integral2
和 integral1
。这样 integral2
为 x
和 y
生成一个网格,integral1
生成 t
值。这样 t
和 x
的值在大小上就不匹配,即使它们是不同网格的一部分。
如前所述,使用 ingetral3
是正确的选择。或者你可以简单地 "fix" 这引入一个循环,但这会导致代码慢得多:
function I = fun1(x)
I=nan(size(x));
for ix=1:numel(x)
I(ix) = integral(@(t)integrand(x(ix),t),-1,1);
end
function f = integrand(x,t)
f = x.^2.*t;
end
end
我这里有一些代码说明了我想在 matlab 中执行的一些积分的嵌套性质。当我 运行 以下代码时,我得到错误
Error using .*
Matrix dimensions must agree.
Error in fun1/integrand (line 7)
f = x.^2.*t;
我现在设置的方式似乎不允许 integral
函数的矢量化输出。我该怎么做才能使我的代码 运行?我在下面评论了我希望函数执行的操作。
我的代码如下:
%主要脚本:
z = linspace(0,10,10);
I = zeros(10,1);
for i = 1:10
I(i) = fun2(z(i));
end
%函数 1 在单独的文件中:
function I = fun1(x)
I = integral(@integrand,-1,1);
function f = integrand(t)
f = x.^2.*t;
end
end
%函数 2 在单独的文件中:
function I = fun2(z)
I = integral2(@integrand,-1,1,-1,1);
function f = integrand(x,y)
f = z.*fun1(x).*y; // here fun1 should return the value for all x that is swept through by integral2 during its call.
end
end
您的代码存在问题,您正在组合使用 integral2
和 integral1
。这样 integral2
为 x
和 y
生成一个网格,integral1
生成 t
值。这样 t
和 x
的值在大小上就不匹配,即使它们是不同网格的一部分。
如前所述,使用 ingetral3
是正确的选择。或者你可以简单地 "fix" 这引入一个循环,但这会导致代码慢得多:
function I = fun1(x)
I=nan(size(x));
for ix=1:numel(x)
I(ix) = integral(@(t)integrand(x(ix),t),-1,1);
end
function f = integrand(x,t)
f = x.^2.*t;
end
end