MATLAB Answers


Using fminunc to find local minimum

Asked by Shenglun Shi on 17 Nov 2012

Hi I was trying to use fminunc to find local minimum when doing Maximum Likelihood Estimation. Here's the code, hope you can help me resolve this: clear all; close all; clc;

sp = xlsread('Data_SP500.xlsx');

sp = sp(1:1000);

global r;

r = price2ret(sp);

[a,b] = fminunc(@garch_likelihood, [0,0,0,0]);

The code for function garch_likelihood is:

function out = garch_likelihood(a0,a1,b1,mu)

global r;

global T;

T = length(r);

out = (-T/2)*log(2*pi);

sigma2 = zeros(T,1);

sigma2(1) = randn^2;

for j = 2:T

    sigma2(j) = a0 + a1*sigma2(j-1)*randn^2 + b1*sigma2(j-1);


for i = 1:T

    out = out - (1/2)*log(sigma2(i)) - (1/2)*((r(i)-mu)/sigma2(i));



I got this error message: Error using garch_likelihood (line 9) Not enough input arguments. Error in fminunc (line 251) f = feval(funfcn{3},x,varargin{:}); Error in prob1 (line 11) [a,b] = fminunc(@garch_likelihood, [0,0,0,0]); Caused by: Failure in initial user-supplied objective function evaluation. FMINUNC cannot continue.


Log in to comment.


1 Answer

Answer by Matt J
on 17 Nov 2012

You need to combine your 4 unknowns into a single vector and make garch_likelihood a function of this vector.


I think I did...

[a,b] = fminunc(@garch_likelihood, [0,0,0,0]);

It takes in the vector [0, 0 ,0, 0], and the garch_likelihood function takes in (a0, a1, b1, mu)


No, you did not. You did pass a length-4 initial guess vector to fminunc, but the input syntax of garch_likelihood is written to take 4 separate scalar variables (a0, a1, b1, mu) as inputs. Instead, you need to rewrite garch_likelihood as follows

function out = garch_likelihood(FourUnknowns)
   a0=FourUnknowns(1); %unpack if convenient


Similarly, you should not expect FMINUNC to return the solution variables as 4 separate variables. You should expect the first output argument to contain a length-4 vector representing the solution and the 2nd argument to contain the optimal value.

[FourUnknownsOptimal,likelihoodOptimal] = fminunc(@garch_likelihood, [0,0,0,0]);

Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!