Reputation: 1301
I know how to perform the single integral using the trapezoidal rule for non-uniform grid. If my function is f(x,y)
, then single integral over dx
in MATLAB would look like
m1=(sum(diff(x,1,2).*(f(:,1:end-1)+f(:,2:end)),2))/2
Now if I have the function f(x,y,z)
how to perform the double integral over dydz
using the trapezoidal rule of non-uniform grid in MATLAB ?
Please note its a non-uniform grid.
Upvotes: 0
Views: 1105
Reputation: 919
Using the built in function trapz
in MATLAB you can accomplish just that. Here's an example:
>> x = -3:.1:3;
y = -5:.1:5;
z = -10:0.1:10;
[X,Y,Z] = meshgrid(x,y,z);
F = X.^2 + Y.^2 + Z.^2;
I = trapz(y,trapz(x,F,2));
I = squeeze(I);
What I'm doing is creating a mesh grid of my data points represented by lowercase x,y,z
, and evaluating the function, in this case X^2+y^2+Z^2
. You would already have alternate data for this. Keep in mind you can always use griddata
to re-grid your data uniformly.
I then use trapz
twice to integrate the x and y dimension. trapz
specifically specifically integrates only over the first matrix dimension that's not equal to 1, allowing me to do this (see documentation here: http://www.mathworks.com/help/matlab/ref/trapz.html).
Finally, I use squeeze on the data to remove all singleton dimensions and return a vector. If I plot the data along the remaining dimension I get:
>> plot(z,I);
Comparing to my original function, which if integrated analytically between -3 <= x <= 3
and -5 <= y <= 5
I obtain: 680 + 60 z^2
. The two are in agreement.
Upvotes: 2