Search code examples
c#carrayscurve-fittingalglib

List<double> to double[,] for ALGLIB


I'm pretty new in C# and I would like to use it to write a software for the calibration of an AFM cantilever. Therefor, I would need to fit a pretty ugly function to the first peak of some none linear data. I thought the ALGLIB package might come in handy for this purpose, which seems relatively easy to apply. In the example of their homepage they use for their X-axis data:

double[,] x = new double[,]{{-1},{-0.8},{-0.6},{-0.4},{-0.2},{0},{0.2},{0.4},{0.6},{0.8},{1.0}};

I have my X-values in a list and would like to use them. How do I get them out of the list and into the double[,]? My last approach was something like this

List<double> xz = new List<double>();
...
double[,] x = new double[,]{xz.ToArray()};

It seems like it has to be in a double[,] array since it's mandatory for the function later

alglib.lsfitcreatef(x, y, c, diffstep, out state);

Could anybody help me with that? Or does anybody can recommend an easier approach for the non-linear fit?

thanks a lot in advance


Solution

  • Here's a simple way to copy the values from your list to your array:

    List<double> xz = // something
    double[,] x = new double[xz.Count, 1];
    for (int i = 0; i < xz.Count; i++)
    {
        x[i, 0] = xz[i];
    }
    

    I couldn't find a better method than this manual copying. ToArray() creates an incompatible type (double[]), and Array.Copy expects the arrays to have the same rank (i.e. number of dimensions).