Thomas Jr
Thomas Jr

Reputation: 15

Nested numerical integration

The problem in the link: http://i.imgur.com/4w9YWTb.png can be integrated analytically and the answer is 4, however I'm interested in integrating it numerically using Matlab, because it's similar in form to a problem that I can't integrate analytically. The difficulty in the numerical integration arises because the function in the two inner integrals is a function of x,y and z and z can't be factored out.

Upvotes: 1

Views: 1438

Answers (2)

A. Donda
A. Donda

Reputation: 8477

Well, this is strange, because on the poster's similar previous question I claimed this can't be done, and now after having looked at Guddu's answer I realize its not that complicated. What I wrote before, that a numerical integration results in a number but not a function, is true – but beside the point: One can just define a function that evaluates the integral for every given parameter, and this way effectively one does have a function as a result of a numerical integration.

Anyways, here it goes:

function q = outer

    f = @(z) (z .* exp(inner(z)));
    q = quad(f, eps, 2);

end

function qs = inner(zs)
% compute \int_0^1 1 / (y + z) dy for given z

    qs = nan(size(zs));
    for i = 1 : numel(zs)
        z = zs(i);
        f = @(y) (1 ./ (y + z));
        qs(i) = quad(f, 0 , 1);
    end

end

I applied the simplification suggested by myself in a comment, eliminating x. The function inner calculates the value of the inner integral over y as a function of z. Then the function outer computes the outer integral over z. I avoid the pole at z = 0 by letting the integration run from eps instead of 0. The result is

4.00000013663955

inner has to be implemented using a for loop because a function given to quad needs to be able to return its value simultaneously for several argument values.

Upvotes: 0

Guddu
Guddu

Reputation: 2437

by no means, this is elegant. hope someone can make better use of matlab functions than me. i have tried the brute force way just to practice numerical integration. i have tried to avoid the pole in the inner integral at z=0 by exploiting the fact that it is also being multiplied by z. i get 3.9993. someone must get better solution by using something better than trapezoidal rule

function []=sofn
clear all

global x y z xx yy zz dx dy

dx=0.05;
x=0:dx:1;
dy=0.002;
dz=0.002;
y=0:dy:1;
z=0:dz:2;

xx=length(x);
yy=length(y);
zz=length(z);

s1=0;
for i=1:zz-1
    s1=s1+0.5*dz*(z(i+1)*exp(inte1(z(i+1)))+z(i)*exp(inte1(z(i))));
end
s1

end

function s2=inte1(localz)
global y yy dy

if localz==0
    s2=0;
else
s2=0;
for j=1:yy-1
    s2=s2+0.5*dy*(inte2(y(j),localz)+inte2(y(j+1),localz));
end
end

end

function s3=inte2(localy,localz)
global x xx dx

s3=0;
for k=1:xx-1
    s3=s3+0.5*dx*(2/(localy+localz));
end

end

Upvotes: 1

Related Questions