I have a user-defined function
function[Rout2] = SSP2(a1,a2,b1,b2,pB)
if a1/b1>a2/b2
if pB<=a1-b1*a2/b2
Rout2 = (a1-pB)/b1;
else
if pB<=a1+a2
Rout2 = (a1+a2-pB)/(b1+b2);
else
Rout2 = 0;
end
end
else
if pB<=a2-b2*a1/b1
Rout2 = (a2-pB)/b2;
else
if pB<=a1+a2
Rout2 = (a1+a2-pB)/(b1+b2);
else
Rout2 = 0;
end
end
end
end
b1,b2,pB
are all parameters. I want to use Matlab integral2
to integrate this function over a1 in [0,t1]
and a2 in [0,t2]
. I originally tried
integral2(SSP2,0,t1,0,t2)
But it does not work. Then I guess it is probably I am passing extra parameters. So I did the following modification
function[R] = NumericalIntegration(b1,b2,pB,t1,t2)
function[Rout2] = SSP2(a1,a2)
if a1/b1>a2/b2
if pB<=a1-b1*a2/b2
Rout2 = (a1-pB)/b1;
else
if pB<=a1+a2
Rout2 = (a1+a2-pB)/(b1+b2);
else
Rout2 = 0;
end
end
else
if pB<=a2-b2*a1/b1
Rout2 = (a2-pB)/b2;
else
if pB<=a1+a2
Rout2 = (a1+a2-pB)/(b1+b2);
else
Rout2 = 0;
end
end
end
end
R = integral2(@SSP2,0,t1,0,t2);
end
Now, inside the function NumericalIntegration
, the function SSP2
can have access to the parameters b1,b2,pB
. I thought it should work. But it does not. And when I call the function NumericalIntegration
in my main program, it generates error "Not enough input arguments". I was wondering is that because the Matlab integral2
can only work with those one-line anonymous function?
The problem here is the way you defined your function. To do a double integration using the built-in functions, the integrand should be properly vectorized.
One way to do it is to rewrite your function using for loops to treat the cases where a1
and a2
are 2D-arrays of dimensions [m,n]
. But you can use MATLAB element-wise multiplication and the logical operators to define your function as:
function[Rout2] = SSP2(a1,a2,b1,b2,pB)
Rout2 = 0*a1;
Rout2 = Rout2 + ((a1-pB)/b1).*(a1/b1>a2/b2).*(pB<=a1-b1*a2/b2) + &
((a2-pB)/b2).*(a1/b1<=a2/b2).*(pB<=a2-b2*a1/b1);
end
And then create the anonymous function and call it as:
b1 = rand;
b2 = rand;
pB = rand;
fun = @(a1,a2) SSP2(a1,a2,b1,b2,pB);
t1 = rand;
t2 = rand;
I = integral2(fun,0,t1,0,t2)
Just define your parameters b1
, b2
and pB
and integration limits t1
and t2
accordingly.