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

5 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Alan Weiss
Alan Weiss le 20 Août 2018
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
  3 commentaires
Lukasz Grzybowski
Lukasz Grzybowski le 11 Mai 2023
What if it would be function of two parameters?
Alan Weiss
Alan Weiss le 11 Mai 2023
The example IS a function of two parameters, x(1) and x(2). Just combine your parameters into the same vector, x.
Alan Weiss
MATLAB mathematical toolbox documentation

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by