Search code examples
matlabsyntax-errorintegral

Double integral of objective function


I want to evaluate the double integral of my objective function (named myfunction, see below) using the build-in-function integral2.

I have tried to run this script;

f = @(r,theta) myfunction(r,theta);
integral2(f,0,2,0,2*pi);

where myfunction is the following function:

function fkt=myfunction(r,theta)
x=r.*cos(theta);
y=r.*sin(theta);
los(:,1)=x;
los(:,2)=y;
norm = (sum( sqrt( los(:,1).^2 + los(:,2).^2)));
fkt=norm*r;
end

I am making the integral in polar coordinates, that why fkt=norm*r.

Matlab gives me the following error message:

>> untitled2
Subscripted assignment dimension mismatch.

Error in myfunction (line 8)
los(:,1)=x;

I can't figure out, what the problem is.


Solution

  • There are two things that can be improved:

    1. los is undefined
    2. los(:,1) is a column while x is a row, so the assignment has to fail.

    You can correct this by defining los and change your assignment. For instance:

    los = NaN(numel(r), 2);
    los(:,1) = x';
    los(:,2) = y';
    

    But, why do you need the variable los? Just remove it and the error will be gone:

    function fkt=myfunction(r,theta)
    x=r.*cos(theta);
    y=r.*sin(theta);
    norm = (sum( sqrt(x.^2 + y.^2)));
    fkt=norm*r;
    end
    

    Best,