arraysmatlabmultidimensional-arrayoctavenumerical-integration

How to obtain integral from a multidimensional array in Matlab?


Let's say we have

A(:,:,1) =

 1     1     1
 1     1     1
 1     1     1


A(:,:,2) =

 2     2     2
 2     2     2
 2     2     2


A(:,:,3) =

 2     2     2
 3     3     3
 2     2     2

How would I perform an integral over each element along the 'page' (i.e. 'z') axis?

Our result matrix M should be 3 x 3, and for example:

M(1:1) would contain the integral of A(1,1,1), A(1,1,2) and A(1,1,3).

M(1:2) would contain the integral of A(1,2,1), A(1,2,2) and A(1,2,3).

And so on.

I'd like to get matrix M like this:

M = 
3.5    3.5    3.5
4      4      4 
3.5    3.5    3.5

Any idea how to do this? I've tried with trapz but no dice.


Solution

  • Just use the DIM parameter from trapz (this works in Octave):

    A = bsxfun ("times", ones (3, 3), permute([1 2 2], [1, 3, 2]));
    A(2, :, 3) = 3;
    M = trapz (A, 3)
    M =
    
       3.5000   3.5000   3.5000
       4.0000   4.0000   4.0000
       3.5000   3.5000   3.5000