Dipole
Dipole

Reputation: 1910

Nested calls to integral and integral2 in Matlab

I have some code here which illustrates the nested nature of some integrals that I want to perform in matlab. When I run the following code I get the error

Error using  .* 
Matrix dimensions must agree.

Error in fun1/integrand (line 7)
   f = x.^2.*t;

it seems that the way I have set it up now does not allow for vectorized output of the integral function. What can I do to make my code run? I have commented below what I want the functions to do.

My code is as follows:

%Main script:

z = linspace(0,10,10);
I = zeros(10,1);

for i = 1:10
    I(i) = fun2(z(i));
end

%Function 1 in separate file:

function I = fun1(x)

I = integral(@integrand,-1,1);

   function f = integrand(t)
   f = x.^2.*t;
   end
end

%Function 2 in separate file:

function I = fun2(z)

I = integral2(@integrand,-1,1,-1,1);

   function f = integrand(x,y)
       f = z.*fun1(x).*y;    // here fun1 should return the value for all x that is swept through by integral2 during its call.
   end
end

Upvotes: 0

Views: 184

Answers (1)

Daniel
Daniel

Reputation: 36720

The problem with your code is you are using integral2 and integral1 in a combination. This way integral2 generates a grid for x and y and integral1 generates the t values. This way the t and x values don't match in size, and even if they would they are part of a different grid.

As already discussed, using ingetral3 is the right choice. Alternatively you could simply "fix" this introducing a loop, but this results in much slower code:

function I = fun1(x)
I=nan(size(x));
for ix=1:numel(x)
    I(ix) = integral(@(t)integrand(x(ix),t),-1,1);
end
   function f = integrand(x,t)
   f = x.^2.*t;
   end
end

Upvotes: 1

Related Questions