How can I find the double integral using Trapezoidal rule?

I want to find the double integral of the following function (sin(x+3*y))^2*exp(x-2*y)/(x^2+2). Limits are x and y from -1 to 1.
N = 5;
x = linspace(-1, 1,N);
y = linspace(-1, 1,N);
dx = diff(x(1:2));
dy = diff(y(1:2));
[x,y] = meshgrid(x,y);
mat = (sin(x+3.*y)).^2.*exp(x-2.*y)/(x.^2+2);
mat(2:end-1,:) = mat(2:end-1,:)*2;
mat(:,2:end-1) = mat(:,2:end-1)*2;
out = sum(mat(:))*dx*dy/4
I edited this code to suit my function but it shows result as NaN with the following message:
In doubletraptest (line 7)
Warning: Matrix is singular to working precision

 Accepted Answer

x=-1:0.1:1;
y=-1:0.1:1;
[X,Y] = meshgrid(x,y);
F=(sin(X+3*Y)).^2.*exp(X-2*Y)./(X.^2+2);
I=trapz(y,trapz(x,F,2))

4 Comments

Is there a way to do this without using 'trapz'?
help integral2
Best wishes
Torsten.
@Salil: I believe your code for trapezoidal double integration would have worked, if it were not for the error in defining 'mat'. You left out the 'dot' in the division symbol, so you got matrix division instead of element-by-element division, and as it happened, your matrix was singular, resulting in a failure of that kind of division. As Birdman pointed out, it should have been:
mat = (sin(x+3.*y)).^2.*exp(x-2.*y)./(x.^2+2);
Of course, it is easier to use 'trapz', called twice.
Thanks! I knew there was something extremely silly with my code!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!