671 |
khor |
1 |
//disable the stl warning of debug information conflicting with names of longer than 255 char.
|
|
|
2 |
#pragma warning( disable :4786 )
|
|
|
3 |
|
|
|
4 |
#include <iostream>
|
|
|
5 |
#include <vector>
|
680 |
janba |
6 |
#include <GEL/CGLA/CGLA.h>
|
|
|
7 |
#include <GEL/LinAlg/Matrix.h>
|
|
|
8 |
#include <GEL/LinAlg/Vector.h>
|
|
|
9 |
#include <GEL/LinAlg/LapackFunc.h>
|
671 |
khor |
10 |
|
|
|
11 |
using namespace std;
|
|
|
12 |
using namespace LinAlg;
|
|
|
13 |
using namespace CGLA;
|
|
|
14 |
|
|
|
15 |
int main()
|
|
|
16 |
{
|
|
|
17 |
// Matrix row and column dimensions
|
|
|
18 |
int N=4,M=4;
|
|
|
19 |
|
|
|
20 |
// Fill the matrix with random values.
|
|
|
21 |
gel_srand(0);
|
|
|
22 |
CMatrix mat(N,M,0);
|
|
|
23 |
for(int i=0;i<N;++i)
|
|
|
24 |
for(int j=0;j<M;++j)
|
|
|
25 |
mat.set(i,j,gel_rand()/double(GEL_RAND_MAX)-0.5);
|
|
|
26 |
|
|
|
27 |
// Create a vector of random values
|
|
|
28 |
CVector b(N);
|
|
|
29 |
for(int i=0;i<N;++i)
|
|
|
30 |
b.set(i, gel_rand()/double(GEL_RAND_MAX)-0.5);
|
|
|
31 |
|
|
|
32 |
// Some output
|
|
|
33 |
cout << "Matrix rows, cols = ";
|
|
|
34 |
cout << mat.Rows() << " , " << mat.Cols() << endl;
|
|
|
35 |
cout << "Matrix: " << mat << endl;
|
|
|
36 |
cout << "Vector: " << b << endl;
|
|
|
37 |
|
|
|
38 |
// Use lapack function to do least squares solution
|
|
|
39 |
CVector x(M);
|
|
|
40 |
x = LinearLSSolve(mat,b);
|
|
|
41 |
cout << "Least squares solution: " << x << endl;
|
|
|
42 |
|
|
|
43 |
// Of course if the system has full rank, we can use
|
|
|
44 |
//CVector LinearSolve(const CMatrix& A,const CVector&b);
|
|
|
45 |
|
|
|
46 |
// Manual (and less efficient least squares solution ...
|
|
|
47 |
CMatrix mat_T = mat.Transposed();
|
|
|
48 |
CMatrix mat2 = mat_T * mat;
|
|
|
49 |
Invert(mat2);
|
|
|
50 |
mat2 = mat2 * mat_T;
|
|
|
51 |
|
|
|
52 |
CVector x2(M);
|
|
|
53 |
x2 = mat2 * b;
|
|
|
54 |
cout << "Least squares solution: " << x2 << endl;
|
|
|
55 |
|
|
|
56 |
}
|