Integration of a 2D matrix using MATLAB

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 15K views
AlonsoMcLaren
Messages
89
Reaction score
2
How to do integration for a 2D matrix using MATLAB?

That is to say, suppose I have a bunch of data points over a rectangular region in xy plane, how to find the integral over this plane?

More explicitly, suppose I want to integrate over a square region, [0,4]x[0,4]

my data is

2 4 5 8 6
6 8 7 8 9
1 0 2 0 1
5 2 1 3 2
2 2 2 1 3

Therefore the value at (3,0) is 5, the value at (1,1) is 8, etc.

How to find the integral of these data over this square region?

If it were a 1D vector I am sure I can do it with trapz. But what about 2D? Thanks
 
Physics news on Phys.org
AlonsoMcLaren said:
Therefore the value at (3,0) is 5, the value at (1,1) is 8, etc.

No. The indices of a matrix in MATLAB always start with 1 and the column is specified first. So 5 is at (1,3) and 8 is at (2,2).

If you use cumtrapz() on your matrix it will return a matrix of the same size:

Code:
[x,y] = meshgrid(0:4,0:4);
I = [2 4 5 8 6; 6 8 7 8 9;1 0 2 0 1; 5 2 1 3 2; 2 2 2 1 3];
cumtrapz(I)

ans =

         0         0         0         0         0
    4.0000    6.0000    6.0000    8.0000    7.5000
    7.5000   10.0000   10.5000   12.0000   12.5000
   10.5000   11.0000   12.0000   13.5000   14.0000
   14.0000   13.0000   13.5000   15.5000   16.5000

The last row is equivalent to the output from trapz(). To visualize:

Code:
plot3(x,y,cumtrapz(I),x,y,I)
view(-84,6)

So the area under the data points is

Code:
sum(trapz(I))

ans =

   72.5000

Of course, this is a bad approximation since the points are far apart and linear behavior is assumed. More data points spaced closer together will give better results.
 
Last edited: