We have MATLAB LM (Levenberg-Marquardt) code which needs to be done in C++. I am interested in buying the commercial edition, but before that I would like to see if it is works with our input parameters or not.
To start with, I tried to run simple input values for LM and It failed to run. Error was -8 and the traget function was throwing infinity at 60th iteration - Refer 1 screenshot.
I have attached the problem with sample input values, which I tried to run it.
Please do let me know how to move forward.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "interpolation.h"
using namespace alglib;
void function_cx_1_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr)
{
// Exponential function of the form: x(1)*exp(x(2)*xdata);
func = c[0] * exp(c[1] * x[0]);
}
int main(int argc, char **argv)
{
//
// In this example we demonstrate exponential fitting
// by f(x) = exp(-c*x^2)
// using function value only.
//
// Gradient is estimated using combination of numerical differences
// and secant updates. diffstep variable stores differentiation step
// (we have to tell algorithm what step to use).
//
real_2d_array x = "[[0.9],[1.5],[13.8],[19.8],[24.1],[28.2],[35.2],[60.3],[74.6],[81.3]]";
real_1d_array y = "[455.2, 428.6, 124.1 ,67.3, 43.2 ,28.1, 13.1, -0.4, -1.3, -1.5]";
real_1d_array c = "[100,-1]";
double epsx = 0.000001;
ae_int_t maxits = 0;
ae_int_t info;
lsfitstate state;
lsfitreport rep;
double diffstep = 0.0001;
//
// Fitting without weights
//
lsfitcreatef(x, y, c, diffstep, state);
lsfitsetcond(state, epsx, maxits);
alglib::lsfitfit(state, function_cx_1_func);
lsfitresults(state, info, c, rep);
printf("%d\n", int(info)); // EXPECTED: 2
printf("%s\n", c.tostring(1).c_str()); // EXPECTED: [498.8309 -0.1013]
return 0;
}
Snapshot 1.Format:
0.000000 -> (100.000000) (-1.000000) (81.300003)
func -> (c[0]) (c[1]) (x[0]))