Reputation: 225
I want to optimize an unconstrained multivariable problem using fminunc
function in MATLAB. Here is an example:
Minimize the function f(w)=x'Ax
Create a file myfun.m:
function f = myfun(x)
f = x'*A*x + b'x
Then call fminunc
to find a minimum of myfun
near x0
:
[x,fval] = fminunc(@myfun,x0).
My problem is that in my algorithm, the matrix A
and vector b
in myfun.m are not fixed, but can be changed over loops, so I cannot type them by hand. How can I pass values to A
and b
?
Upvotes: 1
Views: 265
Reputation: 30589
There are a few options for passing additional arguments to an objective function. For a simple one like yours, you could just make an anonymous function, which will save the values of A
and b
when it was created:
A = myMatA();
b = myVecb();
myfun = @(x) x.'*A*x + b.'*x;
[x,fval] = fminunc(myfun,x0); % use no @ with an anonymous function
The other two options are global variables (yuck!) and nested functions. A nested function version looks like this:
function [x,fval] = myopt(A,B,x0)
[x,fval] = fminunc(@myfunnested,x0);
function y = myfunnested(x)
y = x.'*A*x + b.'*x;
end
end
But I think you would not use fminunc
to solve minimization of x'Ax + b'x
...
Upvotes: 1