Question

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. 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.

Was it helpful?

Solution

Is this all you're looking for (I still don't know what f returns)?:

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. 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:

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). Of course you could equally just use normal functions (which are usually faster and make your code easier to understand by others).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top