简体   繁体   中英

Function for taking a integral in Matlab

I made a function to take intergal Likehood(L,U,gamma,sigma), but there are some error. Here is my Matlab code.

function func=Likelihook(L,U,gamma,sigma)
Lstar=3;
Ustar=20;
gammastar=1.5;
a=0.2;
func=-0.5.*log(2.*pi)-log(sigma)+log(gamma)-log(L.^(-gamma)-U.^(-gamma))+quad(@(y)(log(quad(@(x)(x.^(-gamma-1).*exp(-0.5.*((y-x)./sigma).^2)),L,U)).*gammastar./(sqrt(2*pi).*Lstar.^(-gammastar)-Ustar.^(-gammastar)).*quad(@(x)(x.^(-gammastar-1)./(a.*x).*exp(-0.5.*((y-x)./(a.*x)).^2)),Lstar,Ustar)),-inf,inf) ;

And here is the function i want calculate

http://i.stack.imgur.com/lP1lz.png

Anyone help me?

Explanation

Matlab tries to compute the integration vectorially, so

f = @(x) x;
quad(f(x) x,1,5)

gets evaluated like

sum(f(1:dx:5))

with matlab figuring out what the discretization interval should be. This is computable, because f = @(x) x takes vectorial input.

When you have a double integral, you'll get something like this:

f = @(x,y) x+y;
quad(quad(f(x,y) x,1,5),4:10)

becomes

sum(sum(f(1:dx:5,),4:dy:10))

This will only evaluate if 1:dx:5 and 4:dy:10 happen to have the same number of elements (not very likely).

Solution

You can solve it of course, by adapting your function f so it does take any two vectors as an input, for example by using arrayfun.

For your problem, this is done like this:

func = -0.5.*log(2.*pi)-log(sigma)+log(gamma)-log(L.^(-gamma)-U.^(-gamma)) ...
+quad(@(y)( ...
    log( arrayfun(@(z) quad(@(x)( x.^(-gamma-1).*exp(-0.5.*((z-x)./sigma).^2)),L,U), y) ) ...
    .* gammastar./(sqrt(2*pi).*Lstar.^(-gammastar)-Ustar.^(-gammastar)) ...
    .* arrayfun(@(z) quad(@(x)( x.^(-gammastar-1)./(a.*x).*exp(-0.5.*((z-    x)./(a.*x)).^2)),Lstar,Ustar), y) ...
),-inf,inf) ;

I inserted some linebreaks ( ... ) for easier reading :)

Remarks

I'm not sure if this will lead to solid results for you, because of the integration from -Inf to Inf : in the documentation of quad , it is stated that

If the interval is infinite, [a,Inf), then for the integral of fun(x) to exist, fun(x) must decay as x approaches infinity

so, you'll have to make sure that this is the case, otherwise you'll keep getting NaNs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM