Linear Algebra Example

Example 333. Linear Algebra

FILENAME: example7.cpp

Program:

/*

* This example shows how to use the class RWGenFact<T>

* to do linear algebra with double precision matrices.

*/

 

// Include the RWGenFact<T> class header file:

#include <rw/math/genfact.h>

// Include the double precision matrix header file:

#include <rw/math/genmat.h>

#include <iostream>

// Initial data for the vectors:

const double adata[] = {-3.0, 2.0, 1.0, 8.0, -7.0,

9.0, 5.0, 4.0, -6.0};

const double arhs[] = {6.0, 9.0, 1.0};

int main()

{

// Construct a test matrix and print it out:

RWGenMat<double> testmat(adata,3,3);

std::cout << "test matrix:\n" << testmat << "\n";

/*

* Calculate and print the inverse.

* Note that a type conversion occurs:

* testmat is converted to type RWGenFact<double>

* before the inverse is computed.

*/

std::cout << "inverse:\n" << inverse(testmat);

// Now construct an RWGenFact<double> from the matrix:

RWGenFact<double> LUtest(testmat);

// Once constructed, LUtest may be reused as required.

// Find the determinant:

std::cout << "\ndeterminant\n" << determinant(LUtest)

<< std::endl;

// Solve the linear system testmat*x = rhs:

RWMathVec<double> rhs(arhs, 3);

RWMathVec<double> x = solve(LUtest, rhs);

std::cout << "solution:\n" << x << "\n";

}

Sample Input:

None required.

Sample Output (note that the exact numbers depend on machine precision):

 

test matrix:

3X3

[

-3 8 5

2 -7 4

1 9 -6

]

inverse:

3X3

[

0.025532 0.395745 0.285106

0.068085 0.055319 0.093617

0.106383 0.148936 0.021277

]

determinant:

235

solution:

[

4 1 2

]