User-Defined Type Example
Example 10 – User-Defined Types
FILENAME: example10.cpp
 
/*
* This example shows how to use a user-defined type.
* The number class information is stored in rational.h and
* and rational.cpp. The Rational class is complete, but not
* designed for optimal efficiency. It is included for example
* purposes only.
*/
 
// Include the RWGenFact<T> class header file.
#include <rw/math/genfact.h>
// Include the matrix and vector header files:
#include <rw/math/genmat.h>
#include <rw/math/mathvec.h>
#include <rw/rstream.h>
// Include the user-defined type Rational:
#include "rational.h"
 
// Initial data for the vectors:
const Rational adata[] = {
Rational(-3), Rational(2), Rational(1),
Rational(8), Rational(-7), Rational(9),
Rational(5), Rational(4), Rational(-6)};
const Rational arhs[] = {
Rational(6), Rational(9), Rational(1)};
 
int main()
{
// Construct a test matrix and print it out:
RWGenMat<Rational> 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<Rational>
* before the inverse is computed.
*/
std::cout << "inverse:\n" << inverse(testmat);
 
// Now construct a RWGenFact<Rational> from the matrix:
RWGenFact<Rational> 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<Rational> rhs(arhs, 3);
RWMathVec<Rational> x = solve(LUtest, rhs);
 
std::cout << "solution:\n" << x << "\n";
return 0;
}
 
Sample Input:
None required.
Sample Output:
test matrix:
3x3 [
-3/1 8/1 5/1
2/1 -7/1 4/1
1/1 9/1 -6/1
]
inverse:
3x3 [
6/235 93/235 67/235
16/235 13/235 22/235
5/47 7/47 1/47
]
determinant
235/1
solution:
[
4/1 1/1 2/1
]
Note: compare these values with the results of the example in Linear Algebra Example.