Fit to sum of sinusoidal functionsTop, Main, Index
First step is to import packages:
Then we set seed for rand function with srand:
Define function for generating random number from min value to max value:
As data for fit we generate 100 points with step 0.01 using next function:
Data generation code:
Next we define function we want to minimize:
On input we have pdata dictionary that contains x and y points for calculating residuals. Residuals are calculated as such:
Also we save the function values to calculate the fitted data, and return dictionary containing both lists. For ::tclopt::Mpfit::run procedure we must provide the dictionary with fvec key.
We have 3 parameters, and we can make optimization faster if we provide resasonable limits to parameters values. For that task we create ::tclopt::ParameterMpfit objects and set boundaries for each parameter as [0,20], and then this list will be the input to [::tclopt::mpfit] procedure).
We define optimizer object ::tclopt::Mpfit and added parameters objects to it:
We provide name of our function as an -funct argument, define the number of point -m 100 and data for calculating residuals -pdata $pdata. Also, the important fact: in the order we add parameters to optimizer object the parameters will be passed to minimizing function, and method ::tclopt::Mpfit::run returns final values list under key 'x' in the same order.
Now we are ready to call optimization routine with method ::tclopt::Mpfit::run and collect the results:
The resulted dictionary contains the solution vector x with values of parameters, and miscellanious information about fitting process, part of it we can print:
Results are:
Now we can plot fitted curve, initial data and curve before fitting: