MATLAB Integration of a 2D matrix using MATLAB

Click For Summary
To integrate a 2D matrix in MATLAB, the cumtrapz() function is utilized, which computes the cumulative integral along specified dimensions. For example, given a matrix representing data points over a square region [0,4]x[0,4], the cumtrapz() function can be applied directly to the matrix to yield a new matrix of the same size, reflecting cumulative integrals. The output can be visualized using a 3D plot alongside the original data points. To find the total integral over the region, the trapz() function is used on the matrix, resulting in a total area under the data points. However, it's important to note that this method assumes linear behavior between points, which may lead to inaccuracies if the data points are spaced far apart; denser sampling can improve the approximation.
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:

Similar threads

  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 4 ·
Replies
4
Views
1K
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
5K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K