Minimum Origin Version Required: Origin 8.0 SR0
The following code shows how to use NLFit to fit matrix data.
#include <FDFTree.h> #include <ONLSF.h> #include <wks2mat.h> bool matrix_fit() { // Get Matrix Object data into matrix MatrixLayer ml = Project.ActiveLayer(); if( !ml ) return false; MatrixObject mo = ml.MatrixObjects(0); matrix mat = mo.GetDataObject(); // Get X and Y minimum and maximum respectively // and then gerenate X and Y vectors for the same size of matrix double xmin, ymin, xmax, ymax; mo.GetXY(xmin, ymin, xmax, ymax); int nCols = mat.GetNumCols(); int nRows = mat.GetNumRows(); vector vX(nCols*nRows), vY(nCols*nRows); // Get X and Y vectos by equi-spaced gridding with specified minimum and maximum ocmath_mat_to_regular_xyz(NULL, nRows, nCols, xmin, xmax, ymin, ymax, vX, vY, NULL, true); // Load function from FDF file to tree string strFDF = okutil_get_origin_path(ORIGIN_PATH_SYSTEM, "FitFunc") + "Gauss2D.FDF"; Tree trFF; if(!nlsf_FDF_to_tree(strFDF, &trFF)) return false; // NLFit object NLFit fit; // Set function if( fit.SetFunction(trFF) < 0 ) // If error return false; // Set data NLSFONEDATA arrstDep; // Dependent arrstDep.pdData = mat; arrstDep.nSize = nRows*nCols; NLSFONEDATA arrstIndep[2]; // Independents, here are two, X and Y arrstIndep[0].pdData = vX; arrstIndep[0].nSize = vX.GetSize(); arrstIndep[1].pdData = vY; arrstIndep[1].nSize = vY.GetSize(); if( 0 != fit.SetData(1, &arrstDep, arrstIndep) ) // 0 means OK return false; // Run parameter init code to get parameter init values vector vZ; mat.GetAsVector(vZ, true); // Convert the matrix to vector NumericFunction NF; NF.SetTree(trFF); vector vParameters; // z0, A, xc, w1, yc, w2 if( !NF.ParamInit(vParameters, vX, vY, vZ) ) // Initialize return false; // Output patatmer init values out_str("--- Paramter init values --- "); for(int ii = 0; ii < vParameters.GetSize(); ii++) { printf("param index = %d value is = %1f\n", ii, vParameters[ii]); } // Set paremter values if( 0 != fit.SetParams(vParameters.GetSize(), vParameters) ) // 0 means OK return false; // Perform fitting int nMaxNumIterations = 100; fit.Fit(nMaxNumIterations); // Output the fitted parameter results out_str("--- Paramter result values --- "); for(ii = 0; ii < vParameters.GetSize(); ii++) { printf("param index = %d value is = %1f\n", ii, vParameters[ii]); } return true; }