2
votes

A common way to write the objective function in matlab (including the gradient vector) is the following:

[L,G] = objfun(x) 

where L is the value of objective function, G is the gradient vector and x is a vector of coefficients which I want to optimize.

However, when I include another input (i.e [L,G]=objfun(x,M), where M is a matrix) or when I call another function in the function objfun, the code is not running.

How can I include any inputs and call any functions in the objfun by keeping this format of optimization?

Note that I call the optimization as follows:

[x ,fval] = fminunc(@objfun,x,options) 

where

options = optimoptions(@fminunc,'Algorithm','quasinewton',...
                      'Display','iter','Gradobj','on','TolFun',10^-8)
1
Hey, could you add a minimal working/not working example, i.e. how would you call the optimizer? Which optimizer? Please add that information to your question via "edit".Marcus Müller
Mr Marcus Muller, thanks for the reply. I have already added the information that you have suggestedZenon Taoushianis
thanks you! ah, now things are much easier to answer :)Marcus Müller

1 Answers

3
votes

There's an mathworks help article on passing extra parameters to the objective function:

You can use the @(...) operator to generate an anonymous function handle to your function that will only depend on a single parameter.

a = 4; b = 2.1; c = 4;
f = @(x)objfun(x,a,b,c)

From the original page (where your objfun is parameterfun):

Note: The parameters passed in the anonymous function are those that exist at the time the anonymous function is created. Consider the example

a = 4; b = 2.1; c = 4;
f = @(x)parameterfun(x,a,b,c)

Suppose you subsequently change, a to 3 and run

[x,fval] = fminunc(f,x0)

You get the same answer as before, since parameterfun uses a = 4, the value when f was created.

To change the parameters that are passed to the function, renew the anonymous function by reentering it:

a = 3;
f = @(x)parameterfun(x,a,b,c)