0

我有一个函数 f = @(x,y,z) ...我想用给定的 y 和 z 数值对 x 执行有限数值积分。

目前,我这样做如下 -

f2 = @(x) f(x,5,10)
integral(f2,-1,1)

(5 和 10 实际上只是一些在程序过程中假定某些值的 y 和 z)。

我的问题如下 -

因为我必须对 (y,z) 的许多值进行积分(通常在循环中)。每次,我都必须重新定义一个函数。这大概使我的程序非常慢。有没有更优化的方法来做这个操作,我不必不断地重新定义我的功能。我需要程序运行得更快。

谢谢!

4

2 回答 2

1

匿名函数很慢。重写ff2嵌套函数怎么样?例如:

function result = iterate_trough(A, B)

        result = 0;
        for a = 1:2:A, for b = 5:5:B
                result = result + quad(@f2,-1,1);
        end; end;

        function r  = f(x,y,z),  r  = x+y+z;     end
        function r2 = f2(x),     r2 = f(x,a,b);  end
end

这会降低代码的灵活性吗?

稍后编辑:甚至更好,消除调用的开销f

function result = iterate_trough(A, B)

        result = 0;
        for a = 1:2:A, for b = 5:5:B
                result = result + quad(@f2,-1,1);
        end; end;

        function r2 = f2(x),  r2 = x+a+b;  end
end
于 2013-04-17T01:12:13.443 回答
0

I was able to speed up some looping code (an MCMC) with many integrals using the composite Simpson's method detailed in "Writing Fast Matlab Code" available at the File Exchange:

http://www.mathworks.com/matlabcentral/fileexchange/5685

From the document, here is a one dimensional integration as an example:

h = (b − a)/(N−1);
x = (a:h:b).';
w = ones(1,N); w(2:2:N−1) = 4; w(3:2:N−2) = 2; w = w*h/3; 
I = w * f(x);

The document shows 2 and 3d examples as well.

As a downside, the code forgoes some of the adaptive step size in some of the built-in quadrature methods. However, this method is so blazingly fast, I was able to just brute-force integrate to such a high precision that this isn't an issue. (My integrals are all relatively tame, though.)

Hope this helps.

于 2013-04-17T04:37:48.107 回答