MATLAB: How to use fminsearch with a symbolic function with a variable number of symbols

fminsearchsymbolic function

Hello Matlab community,
I am struggling with an optimization problem for which I want to use the function fminsearch. The following example is as minimized as possible. I want to have a variable number of parameters and the splitting of the function "funfun" into "fun1" and "fun2" is necessary. The resulting function in this example is the Rosenbrock's function from the fminsearch documentation page ( fminsearch ). I am using Matlab 2014a.
numPar = 2;
a = sym('a', [1 numPar]);
fun1 = symfun(100*(a(2)-a(1)^2)^2, a);
fun2 = symfun((1-a(1))^2, a);
funfun = fun1 + fun2
a0 = [-1.2, 1];
fminsearch(funfun,a0)
This code runs into the error:
Error using symfun/subsref (line 135)
Symbolic function expected 2 inputs and received 1.
Error in fminsearch (line 190)
fv(:,1) = funfcn(x,varargin{:});
Thanks for your help in advance! Cheers

Best Answer

Before running fminsearch, convert your symbolic expression to a MATLAB function by using matlabFunction:
myfun = matlabFunction(funfun,'Vars',{a});
a0 = [-1,1];
[x,fval,exitflag,output] = fminsearch(myfun,a0)
When I ran this I got the following result:
x =
1.0000 1.0000
fval =
4.0576e-10
exitflag =
1
output =
struct with fields:
iterations: 100
funcCount: 187
algorithm: 'Nelder-Mead simplex direct search'
message: 'Optimization terminated:↵ the current x satisfies the termination criteria using OPTIONS.TolX of 1.000000e-04 ↵ and F(X) satisfies the convergence criteria using OPTIONS.TolFun of 1.000000e-04 ↵'
Alan Weiss
MATLAB mathematical toolbox documentation