# LeastSquares

VTKExamples/Cxx/Math/LeastSquares

### Description¶

This example solves XM = Y (an interesting way to write Ax = b).

In particular, we are trying to solve

     [-2](1)

 M = (1)

     (2)


It currently does not work.

Question

### Code¶

LeastSquares.cxx

#include <vtkSmartPointer.h>
#include <vtkMath.h>

/* allocate memory for an nrow x ncol matrix */
template<class TReal>
TReal **create_matrix ( long nrow, long ncol )
{
typedef TReal* TRealPointer;
TReal **m = new TRealPointer[nrow];

TReal* block = ( TReal* ) calloc ( nrow*ncol, sizeof ( TReal ) );
m = block;
for ( int row = 1; row < nrow; ++row )
{
m[ row ] = &block[ row * ncol ];
}
return m;
}

/* free a TReal matrix allocated with matrix() */
template<class TReal>
void free_matrix ( TReal **m )
{
free ( m );
delete[] m;
}

int main(int, char *[])
{

// Solve XM = Y;

int numberOfSamples = 3;
int numberOfVariables = 2;
double **x = create_matrix<double> (numberOfSamples, numberOfVariables);
x = 1; x = 4;
x = 1; x = 2;
x = 2; x = 3;

double **m = create_matrix<double> ( numberOfVariables, 1 );

double **y = create_matrix<double> ( numberOfSamples, 1 );
y = -2;
y = 6;
y = 1;

vtkMath::SolveLeastSquares(numberOfSamples, x, numberOfVariables, y, 1, m);

std::cout << "Solution is: " << m << " " << m << std::endl;

// Solution should be [3; -1];
free_matrix(x);
free_matrix(m);
free_matrix(y);

return EXIT_SUCCESS;
}


### CMakeLists.txt¶

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)

project(LeastSquares)

find_package(VTK COMPONENTS
vtkCommonCore QUIET)
if (NOT VTK_FOUND)
message("Skipping LeastSquares: ${VTK_NOT_FOUND_MESSAGE}") return () endif() message (STATUS "VTK_VERSION:${VTK_VERSION}")
if (VTK_VERSION VERSION_LESS "8.90.0")
# old system
include(${VTK_USE_FILE}) add_executable(LeastSquares MACOSX_BUNDLE LeastSquares.cxx ) target_link_libraries(LeastSquares PRIVATE${VTK_LIBRARIES})
else ()
# include all components
target_link_libraries(LeastSquares PRIVATE ${VTK_LIBRARIES}) # vtk_module_autoinit is needed vtk_module_autoinit( TARGETS LeastSquares MODULES${VTK_LIBRARIES}
)
endif ()


cd LeastSquares/build


If VTK is installed:

cmake ..


If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:

cmake -DVTK_DIR:PATH=/home/me/vtk_build ..


Build the project:

make


and run it:

./LeastSquares


WINDOWS USERS

Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.