Search code examples
matlabnumerical-integration

Numerically integrate in Matlab without requiring vector input


The following is a generalisation of my problem

function E = FunctionIntegration(S)
    I = @(f) log(det(4 * S(f))); 
    E = integral(I, -pi, pi)

S is a function handle that takes scalar input f and returns a matrix. When I try and run this function I get a Inner matrix dimensions must agree error.

I understand that integral requires the function I to take vector input and that's where the problem lies but in this case I don't see a way of accommodating that as I must then pass this vector to function S which returns a matrix. Is there a way around this?

Note an example of S could be:

S = @(f) [f 0; 0 1]

Obviously in this case the integral is easy to do analytically but the function S can be any scalar to matrix transformation.


Solution

  • Your problem is that integral passes an array of values to I. But your I only expects a scalar. Try this:

    function E = functionIntegration(S)
        I = @(x) arrayfun(@(f) log(det(4 * S(f))), x);
        E = integral(I, -pi, pi);
    end
    

    I've wrapped your integrand into a call to arrayfun which will loop over the array passed in by integral and calculates the integrand for each entry:

    >> S = @(x) x * eye(3, 3);
    >> functionIntegration(S)
    
    ans =
    
      28.8591 + 9.8696i