Matrix Example
As the next example shows, using matrices is no more complicated than using vectors. Here we use class RWGenMat<T> to define and print out the matrix A:
 
#include <rw/math/genmat.h> // 1
#include <iostream.h>
int main()
{
RWGenMat<float> A("2x3[1 2 3 4 5 6]"); // 2
A(1,1) = 0; // 3
cout << A; // 4
}
//1 This statement declares the class RWGenMat<T>, a matrix of elements of type T.
//2 Here we define A to be a matrix with 2 rows and 3 columns of floating point numbers, initialized using a character string. The format of the string is the same as that expected by the stream extraction operator, operator>>(istream& RWGenMat<float>).
The implementation of this constructor is a nice example of the power of abstraction provided by the iostream stream library. Rather than parse the string directly in the constructor, we construct an istream using the contents of the string as a source, then use the stream extraction operator >> to extract the matrix. Thus, the same code is used to translate an ASCII representation to a matrix, whether the input is from the keyboard (using the istream cin), from a file (using an ifstream), or from a C++ character string. Thanks to the iostream library, it's easy to a achieve this level of reuse.
//3 In this line, the middle entry in the bottom row of the matrix A is set to 0. The expression A(1,1) is a subscripting expression; it returns a reference to entry 1,1 in the matrix. Subscripting is explained in more detail in Subscripting and Advanced Subscripting.
//4 In the last line, the matrix is printed out.