MATLAB Answers

Finding the minimum of a complicated function with variables and parameters

2 views (last 30 days)
Robert Corns
Robert Corns on 15 Sep 2021
Answered: Jeff Miller on 16 Sep 2021
I'm trying to understand how to use fminsearch to find the minimum of a function that is passed both parameters and variables.
The function is given a list of points in an array p as a set of parameters and a list of variables x as an array. The values of x define different curves (sinewaves or lines). The function finds the distance of the closest curve to each point and then squares that and sums it over all points. Different points will be closer to different curves.
So I have a function with syntax like
SSQ = leastsquares(p,x)
SSQ is a positive number and the objective is to vary different curves (different x's) to find the optimal set of x-values (smallest SSQ).
The instructions for fminsearch describe how to refer to a function defined via a file (but not parameters) or a function with parameters but it is defined in-line (no file). I'm looking for how to use fminsearch with a function that is defined by a file but also has parameters.
Any help would be appreciated.
Here is a toy example of this problem.
x = [0:0.01:2*pi()];
A = 10;
B = 20;
phi = pi()/2;
theta = pi()/4;
y = A*sin(x+phi);
z = B*sin(x+theta);
%this produces two sinewaves with different amplitudes and phases.
%The (x, y) and (x z) are fixed points treated like parameters
%We define two sinewaves with varibles, a, b, alpha and beta
%initial "guess"
a = 5;
b = 100;
alpha = 0;
beta = pi()/2;
%The objective is to optimize the sum of squares so that we find
%something like a = A, b = B, alpha = phi and beta = theta
%The two sinewaves we are looking at are
%sine1 = a sin(x + alpha);
%sine2 = b sin(x + beta);
%The function is
SSQ = leastsquares(x, y, z, a, b, alpha, beta)
%This function takes each point (x, y) and finds the closest of the two sinewave "guesses" for its distance
%Likewise for each point (x, z).
%Each point is assigned a distance this way. So then the function squares these and sums them to make SSQ,

Answers (1)

Jeff Miller
Jeff Miller on 16 Sep 2021
If I understand the problem correctly, then this should be close to what you want:
function bestEsts = MyOuterFn(x,y)
MyErrFn = @(parms) leastsquares(x,y,parms(1),parms(2),parms(3),parms(4));
initialGuess = [5, 100, 0, pi()/2];
bestEsts = fminsearch(MyErrFn,initialGuess)

Community Treasure Hunt

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

Start Hunting!