简体   繁体   English

如何编写一个包含数值积分的函数?

[英]How to write a function which includes numerical integration?

I need to calculate the integration in many points. 我需要在许多方面计算积分。 So, 所以,

f = f(r,theta,k,phi); 
q =integral2(f,0,1,0,2*pi,'AbsTol',0,'RelTol',1e-10); % integration should be by k and phi

I want the q to be a function of r and theta that I can call it anytime to calculate the integration in the given r and theta point. 我希望q是r和theta的函数,我可以随时调用它来计算给定r和theta点的积分。 How can I do this? 我怎样才能做到这一点? The problem is that I couldn't use the indefinite @ function or matlabFunction() methods, because it seems that the integration is done first and when Matlab detects that it doesn't have all arguments defined, it brings some errors. 问题是我不能使用不确定的@ function或matlabFunction()方法,因为似乎首先完成了集成,并且当Matlab检测到未定义所有参数时,会带来一些错误。

Is this all you're looking for (I still don't know what f returns)?: 这就是您要查找的全部内容(我仍然不知道f返回什么)吗?:

r = ...     % Define
theta = ... % Define
g = @(k,phi)f(r,theta,k,phi); % g is now a function of k and phi
q = integral2(g,0,1,0,2*pi,'AbsTol',0,'RelTol',1e-10);

This creates an anonymous function g where the values of r and theta are captured as parameters and k and theta are still arguments. 这将创建一个匿名函数g ,其中rtheta的值被捕获为参数,而ktheta仍然是参数。 This concept is known as a closure in computer science. 这个概念在计算机科学中被称为闭包

If you want to turn the whole thing into a function of r and theta that returns q you can can create the following anonymous function: 如果要将整个事情都变成rtheta的函数并返回q ,则可以创建以下匿名函数:

q = @(r,theta)integral2(@(k,phi)f(r,theta,k,phi),0,1,0,2*pi,'AbsTol',0,'RelTol',1e-10);

that you can call with q(r,theta) . 您可以使用q(r,theta)进行调用。 Of course you could equally just use normal functions (which are usually faster and make your code easier to understand by others). 当然,您同样可以只使用常规函数(通常更快,并且使您的代码更易于他人理解)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM