MATLAB Answers


How to calculate a function of multiple variables which also has an integral in its definition?

Asked by AP
on 30 Oct 2012

Dea All,

I have the following function whose definition needs an integral to be evaluated. The integral itself is dependent on the function input variables.

r0 = 0.5;
z0 = 0.5;
G(r,z,z-z0) = 1/2*r*r0^2 * integral(cos(lambda)/sqrt((r^2+r0^2-2*r*r0*cos(lambda)+(z-z0)^2)) dlambda, -pi, pi);

Could someone please help me how I can get for example G(0.75, 0.75, 0.25)? My final goal is to find G over a rectangular meshgrid.





No products are associated with this question.

2 Answers

Answer by Matt J
on 30 Oct 2012

Create an anonymous function for the integrand as a function of lambda

G=@(r,z,z-z0)  1/2*r*r0^2 * integral(@(lambda) cos(lambda)/sqrt((r^2+r0^2-2*r*r0*cos(lambda)+(z-z0)^2)) , -pi, pi);


This is the new definition:

G=@(r,z,z_minus_z0)  1/2*r*r0^2 * integral(@(lambda) cos(lambda)/sqrt((r^2+r0^2-2*r*r0*cos(lambda)+z_minus_z0^2)) , -pi, pi);
feval(G, 0.75, 0.75, 0.25)

I don't see z anywhere on the RHS. Why not just have


Replace all the * and / by elementwise operations .* and ./

G=@(r,z,z_minus_z0) 1/2.*r.*r0^2 .* ... integral(@(lambda) cos(lambda)./sqrt((r.^2+r0.^2-2.*r.*r0.*cos(lambda)+z_minus_z0.^2)) , -pi, pi);

Answer by Star Strider
on 30 Oct 2012

You need to ‘vectorize’ it:

r0 = 0.5;
z0 = 0.5;
r = 1;
z = 1;
G = @(r,z,z0) 1/2.*r.*r0.^2 .* integral(@(lambda) cos(lambda)./sqrt((r.^2+r0.^2-2.*r.*r0.*cos(lambda)+(z-z0).^2)) , -pi, pi);


Thank @Star Strider. I decided to put all the variables into the functioin definition and did very similar to what you did. I don't know why it does not evaluate G.

r0 = 0.5;
z0 = 0.5;
r = 1;
z = 1;
G=@(r, r0, z, z0)  1/2*r*r0^2 * integral(@(lambda) cos(lambda)/sqrt((r^2+r0^2-2*r*r0*cos(lambda)+(z-z0)^2)) , -pi, pi);

I get this error:

Error using integralCalc/finalInputChecks (line 515)
Output of the function must be the same size as the input. If FUN is an array-valued integrand, set the 'ArrayValued'
option to true.

Thanks all. Runs perfectly with elementwise operations.

r0 = 0.5;
z0 = 0.5;
r = 1;
z = 1;
G=@(r, r0, z, z0)  1/2.*r.*r0^2 .* integral(@(lambda) cos(lambda)./sqrt((r.^2+r0.^2-2*r.*r0.*cos(lambda)+(z-z0).^2)) , -pi, pi);
ans =

You have to vectorize it using the ‘dot’ operators:

G = @(r, r0, z, z0) 1/2.*r.*r0.^2 .* integral(@(lambda) cos(lambda)./sqrt((r.^2+r0.^2-2.*r.*r0.*cos(lambda)+(z-z0).^2)) , -pi, pi);

See if that works as you want it to.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!