Subversion Repositories gelsvn

Rev

Rev 107 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
107 bj 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>
417 jrf 6
#include "CGLA/CGLA.h"
107 bj 7
#include "LinAlg/Matrix.h"
8
#include "LinAlg/Vector.h"
9
#include "LinAlg/LapackFunc.h"
10
 
11
using namespace std;
12
using namespace LinAlg;
417 jrf 13
using namespace CGLA;
107 bj 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.
417 jrf 21
		gel_srand(0);
107 bj 22
		CMatrix mat(N,M,0);
23
		for(int i=0;i<N;++i)
24
				for(int j=0;j<M;++j)
417 jrf 25
						mat.set(i,j,gel_rand()/double(GEL_RAND_MAX)-0.5);
107 bj 26
 
27
		// Create a vector of random values
28
		CVector b(N);
29
		for(int i=0;i<N;++i)
417 jrf 30
				b.set(i, gel_rand()/double(GEL_RAND_MAX)-0.5);
107 bj 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
}