Search code examples
matlabnumericalintegral

numerical integration of matrix in Matlab


I have to numerically evaluate, in Matlab, the integral of the product of two functions A(x,y) and B(x,y). These two functions are in 2-dimensional array form. The integral should read as following

$ C(x,z)=\int_{a}^{b} dy' A(x,y')B(y',z) $

I understand that the function such as "trapz" are for numerical integration of arrays of data, but I do not understand ho to adapt to my case.

thank you

Giuseppe


Solution

  • To guide you I will build some (square) matrix functions

    %// Problem size.
    n = 3;
    %// Auxiliary constant matrices.
    D1 = rand(n, n);
    D2 = rand(n, n);
    D3 = rand(n, n);
    D4 = rand(n, n);
    %// Matrix functions and product.
    A = @(x,y) x^2*D1.^2 + y*D2;
    B = @(y,z) (log(y)+z)*D3.^3 - z*sin(D4);
    P = @(x,y,z) A(x,y)*B(y,z);
    

    In this way P is a function of three variables, now we will integrate it in y, when x and z are both 0.

    a = 0;
    b = 1;
    integral(@(y) P(0,y,0), a, b, 'ArrayValued', true)
    

    To generalize the solution to arbitrary domains we can build a new function in (x,z)

    Int = @(x,z) integral(@(y) P(x,y,z), a, b, 'ArrayValued', true);
    

    and define a mesh

    x = linspace(-1, 1, 11);
    z = linspace(-2, 2, 21);
    [X, Z] = meshgrid(x, z);
    

    Now we can evaluate the integral on the whole mesh.

    C = arrayfun(Int, X(:), Z(:), 'UniformOutput', false);
    

    In this way C will contain all the integrals, stored in a 1D array of cells.

    As a check we can get the result at (x,z) = (0,0) by calling

    C{sub2ind([11 21], 6, 11)}