Augustus 3.4.0
Loading...
Searching...
No Matches
matrix.hh
1/*
2 * matrix.hh
3 *
4 * License: Artistic License, see file LICENSE.TXT or
5 * https://opensource.org/licenses/artistic-license-1.0
6 */
7
8#ifndef _MATRIX_HH
9#define _MATRIX_HH
10
11// standard C/C++ includes
12#include <vector>
13#include <ostream> // for operator<<
14
15
16using namespace std;
17
26template <class T>
27class Matrix {
28public:
30 typedef T value_t;
31public:
35 Matrix(int n = 0, int m = 0) {
36 init(n,m);
37 }
42 delete[] data;
43 }
47 value_t* operator[] ( int i ) {
48 return data + i*width;
49 }
53 const value_t* operator[] ( int i ) const {
54 return data + i*width;
55 }
59 value_t& operator() ( int i, int j ) {
60 return (*this)[i][j];
61 }
65 const value_t& operator() ( int i, int j ) const {
66 return (*this)[i][j];
67 }
71 vector<T> getRow(int i) const {
72 return vector<T>(data + i*width, data + (i+1)*width);
73 }
77 vector<T> getColumn(int j) const {
78 vector<T> result;
79 result.reserve(height);
80 for (value_t* p = data + j; p < data + size; p+=width)
81 result.push_back(*p);
82 return result;
83 }
87 int getColSize( ) const {
88 return height;
89 }
93 int getRowSize( ) const {
94 return width;
95 }
99 void operator=(const Matrix<value_t>& mat) {
100 resize(mat.height, mat.width);
101 for (int i=0; i<size; i++)
102 data[i] = mat.data[i];
103 }
104 void assign(int n, int m, value_t t = value_t()) {
105 resize(n,m);
106 for (int i=0; i<size; i++)
107 data[i] = t;
108 }
109 friend ostream& operator<<(ostream& out, const Matrix<value_t>& mat) {
110 for (int i = 0; i < mat.size; i++) {
111 out << mat.data[i];
112 if (i+1 % mat.width)
113 out << "\t";
114 else
115 out << endl;
116 }
117 return out;
118 }
119
120private:
121 void resize(int n = 0, int m = 0) {
122 if (n == height && m == width)
123 return;
124 delete[] data;
125 init(n,m);
126 }
127 void init(int n = 0, int m = 0) {
128 if (n>0 && m>0) {
129 height=n; width=m; size=n*m;
130 data = new value_t[size];
131 } else {
132 size=height=width=0; data=0;
133 }
134 }
135 int height; // n
136 int width; // m
137 int size; // n*m;
138 value_t *data; // the nxm matrix
139};
140
141#endif // _MATRIX_HH
142
A simple matrix class. Base class for all mathematical matrix objects.
Definition matrix.hh:27
value_t * operator[](int i)
Definition matrix.hh:47
T value_t
The type of the stored values.
Definition matrix.hh:30
vector< T > getRow(int i) const
Definition matrix.hh:71
~Matrix()
Definition matrix.hh:41
Matrix(int n=0, int m=0)
Definition matrix.hh:35