00001 #ifndef ANIMAL_MATRIX_H
00002 #define ANIMAL_MATRIX_H
00003
00007 #include <iostream>
00008 #include <vector>
00009 #include <animal/linear.h>
00010
00011
00012 namespace animal{
00013
00014 template<class T> struct Matrix;
00015
00017 template<class T>
00018 struct matrix_traits<Matrix<T> >
00019 {
00020 typedef T value_type;
00021 static T ZERO() { return 0; }
00022 static T ONE() { return 1; }
00023 };
00024
00025
00026
00034 template<class T>
00035 struct Matrix
00036 {
00037
00039 Matrix( int nrow=0, int ncol=0 )
00040 : nr( nrow )
00041 , nc( ncol )
00042 {
00043 assert( nr >=0 ); assert( nc>=0 );
00044 value.resize(nr*nc);
00045 }
00046
00048 void resize( int r, int c ){
00049 nr = r;
00050 nc = c;
00051 value.resize(nr*nc);
00052 }
00053
00055 void fill( const T& v ){
00056 typename std::vector<T>::iterator i=value.begin(), iend=value.end();
00057 while( i!=iend )
00058 *i++ = v;
00059 }
00060
00062 void setIdentity() {
00063 assert( nrows() == ncols() );
00064 fill( matrix_traits<Matrix<T> >::ZERO() );
00065 for( int i=0; i<nr; ++i )
00066 (*this)[i][i] = matrix_traits<Matrix<T> >::ONE();
00067 }
00068
00070 T* operator[] (int r)
00071 {
00072 assert( r>=0 ); assert( r<nr );
00073 return &(value[nc*r]);
00074 }
00075
00077 const T* operator[] (int r) const
00078 {
00079 assert( r>=0 ); assert( r<nr );
00080 return &(value[nc*r]);
00081 }
00082
00084 int nrows() const { return nr; }
00085
00087 int ncols() const { return nc; }
00088
00090 template<class U> inline friend
00091 ::std::ostream& operator << (::std::ostream& out, const Matrix<U>& m){
00092 for( std::size_t i=0; i<animal::nrows(m); ++i ){
00093 for( std::size_t j=0; j<animal::ncols(m); ++j )
00094 out << m[i][j] << " ";
00095 out << "\n";
00096 }
00097 return out;
00098 }
00099
00101 template<class U> inline friend
00102 ::std::istream& operator >> (::std::istream& in, animal::Matrix<U>& m )
00103 {
00104 for( std::size_t i=0; i<animal::nrows(m); ++i )
00105 for( std::size_t j=0; j<animal::ncols(m); ++j )
00106 in >> m[i][j];
00107 return in;
00108 }
00109
00110
00111 private:
00112 std::vector<T> value;
00113 int nr;
00114 int nc;
00115
00116 };
00120
00121
00123 template<class T> inline
00124 std::size_t nrows( const Matrix<T>& m ){ return m.nrows(); }
00125
00127 template<class T> inline
00128 std::size_t ncols( const Matrix<T>& m ){ return m.ncols(); }
00129
00131 template<class T> inline
00132 const Matrix<T>& m_output(const Matrix<T>& m){ return m; }
00133
00135 template<class T> inline
00136 Matrix<T>& m_input(Matrix<T>& m){ return m; }
00137
00138
00139
00140
00141 }
00142
00143
00144
00145 #endif