Example: math_leastsquares_example
C++ example source code:
/* _ | | Mobile Robot Programming Toolkit (MRPT) _ __ ___ _ __ _ __ | |_ | '_ ` _ \| '__| '_ \| __| https://www.mrpt.org/ | | | | | | | | |_) | |_ |_| |_| |_|_| | .__/ \__| https://github.com/MRPT/mrpt/ | | |_| Copyright (c) 2005-2025, Individual contributors, see AUTHORS file See: https://www.mrpt.org/Authors - All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include <mrpt/gui/CDisplayWindowPlots.h> #include <mrpt/math/utils.h> // normalize() #include <iostream> #include <mrpt/math/interp_fit.hpp> using namespace mrpt::math; using namespace mrpt::gui; using namespace std; // ------------------------------------------------------ // TestLeastSquares // ------------------------------------------------------ void TestLeastSquares() { CVectorDouble x, y; normalize(x, y); const double X[] = {1, 2, 3, 4}; const double Y[] = {6, 5, 7, 10}; loadVector(x, X); loadVector(y, Y); // x points for plotting the least squres line against. CVectorDouble Ts; linspace(-3.0, 8.0, 100, Ts); CVectorDouble Is; mrpt::math::leastSquareLinearFit(Ts, Is, x, y); CDisplayWindowPlots win("Result of linear least squares"); win.plot(Ts, Is); win.axis_fit(); win.axis_equal(); win.plot(x, y, ".3r", "training_points"); win.waitForKey(); } int main(int argc, char** argv) { try { TestLeastSquares(); return 0; } catch (const std::exception& e) { std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << std::endl; return -1; } catch (...) { printf("Another exception!!"); return -1; } }