owner
owner

Reputation: 743

Matlab @fminunc objective function optimization

I am currently practicing a simple function optimization in Matlab and hope you could provide with little assistance / explanation on the following error:

%quadramin.m
function z=quadramin(param,data);
z=data.*(param(1).^2 - param(2).^3)+3;

%quadramin_lik.m
function quadlik = quadramin_lik(param,data);
%pseudo/ad-hoc log-likelihood function
quadlik = quadramin(param,data)- 10;

%script.m
data=trnd(5,6,1);
param0=[2,3];
[param_eq,exitflag,output,grad,hessian] = ... 
fminunc(@(param) quadramin_lik(param,data),param0)

Output after executing %script.m: Error using fminunc (line 333) User supplied objective function must return a scalar value.

ps: It looks paradoxical as the user-defined functions quadramin && quadramin_lik do return values.

Thanks

Upvotes: 0

Views: 1519

Answers (1)

rayryeng
rayryeng

Reputation: 104503

Both your functions return a vector of values whereas fminunc requires that the function returns a scalar / single value. The error is pretty clear. The function fminunc is trying to find the best solution that minimizes a cost function, so what you need to supply is a cost function.

Therefore, perhaps try summing the results in each function before returning them.... but doing that doesn't guarantee a global minimum because fminunc assumes that your cost function is convex. However, judging from your comments as you are computing log likelihoods, then summing is what you should be doing any way!

Upvotes: 2

Related Questions