Search code examples
matlabmatrixnumerical-integration

Numerical integration, dimensions do not agree despite use of .^ and .*


I have an issue with Matlab integration. It tells me that there is an error about dimensions. However they do agree and operations are properly done using vectorized operators (.^ .* etc...). It is simple code yet I am stuck

A = 1:10;
B = 1:10;

K_fun = @(x) (x ./ sqrt((x + A.^2 ) .* (x + B.^2) .* (x + B.^2)) );
K = integral( K_fun, 0,Inf );

and here the error message in the command window:

Error using  + 
Matrix dimensions must agree.

Error in @(x)(x./sqrt((x+A.^2).*(x+B.^2).*(x+B.^2)))

Error in integralCalc/iterateScalarValued (line 314)
                fx = FUN(t);

Error in integralCalc/vadapt (line 133)
            [q,errbnd] = iterateScalarValued(u,tinterval,pathlen);

Error in integralCalc (line 84)
        [q,errbnd] = vadapt(@AToInfInvTransform,interval);

Error in integral (line 89)
Q = integralCalc(fun,a,b,opstruct);

Error in PROVA_New_Drag3 (line 21)
K = integral( K_fun , 0 , Inf);

Thank you in advance


Solution

  • It evaluates both your integration limits in a vector, so effectively your xin the function is [0 Inf], which is why the lengths don't agree.

    You can set the 'ArrayValued' flag to true in the integral call

    K = integral( K_fun, 0,Inf,'ArrayValued', true );
    

    to get it to evaluate them separately.

    I got another warning about a singularity but this is likely because you're using 0, infinity and division so it's related more to your function than the integration call. It might help to to sprinkle some eps around in K_fun.

    UPDATE: Please see Troy's explanation of the singularity warning and note that eps won't actually help with that.