Search code examples
matlabnumerical-integration

"Matrix dimensions must agree" error when computing integral


I am having a problem in finding out the error in the following equation in MATLAB:

a=@(z,q)(z.^2 + q.^2);
a1=@(q) integral(@(z) a(z,q),1,10);

First I want to do an finite integral of a in z only, within numerical limits, lets say 1 and 10, and then I want to plot a1 with respect to q. When I execute the above with the following command:

plot(linspace(0,3e8), a1(linspace(0,3e8)))

I got the following error:

Matrix dimensions must agree.

Error in untitled>@(z,q)(z.^2+q.^2)

Error in untitled>@(z)a(z,q)

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

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

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

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

Error in untitled>@(q)integral(@(z)a(z,q),1,10)

Here is a screenshot.

Can anyone point out the error. Note: I would like to have both z and q as vector


Solution

  • The MATLAB function integral computes a single integral by default, not an array of integrals. The option 'ArrayValued' will allow you to integrate a function that returns multiple values, such as your a:

    a = @(z,q)(z.^2 + q.^2);
    x = linspace(0,3e8);
    y = integral(@(z)a(z,q),1,10,'ArrayValued',true);
    plot(x,y)