Example: math_leastsquares_exampleΒΆ

C++ example source code:

/* +------------------------------------------------------------------------+
   |                     Mobile Robot Programming Toolkit (MRPT)            |
   |                          https://www.mrpt.org/                         |
   |                                                                        |
   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |
   | See: https://www.mrpt.org/Authors - All rights reserved.               |
   | Released under BSD License. See: https://www.mrpt.org/License          |
   +------------------------------------------------------------------------+ */

#include <mrpt/gui.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;
    }
}