00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #include <RcppMatrix.h>
00024
00025 template <typename T>
00026 RcppMatrix<T>::RcppMatrix(SEXP mat) {
00027
00028 if (!Rf_isNumeric(mat) || !Rf_isMatrix(mat))
00029 throw std::range_error("RcppMatrix: invalid numeric matrix in constructor");
00030
00031
00032 SEXP dimAttr = Rf_getAttrib(mat, R_DimSymbol);
00033 dim1 = INTEGER(dimAttr)[0];
00034 dim2 = INTEGER(dimAttr)[1];
00035
00036
00037
00038 int i,j;
00039 int isInt = Rf_isInteger(mat);
00040 T *m = (T *)R_alloc(dim1*dim2, sizeof(T));
00041 a = (T **)R_alloc(dim1, sizeof(T *));
00042 for (i = 0; i < dim1; i++)
00043 a[i] = m + i*dim2;
00044 if (isInt) {
00045 for (i=0; i < dim1; i++)
00046 for (j=0; j < dim2; j++)
00047 a[i][j] = (T)(INTEGER(mat)[i+dim1*j]);
00048 }
00049 else {
00050 for (i=0; i < dim1; i++)
00051 for (j=0; j < dim2; j++)
00052 a[i][j] = (T)(REAL(mat)[i+dim1*j]);
00053 }
00054 }
00055
00056 template <typename T>
00057 RcppMatrix<T>::RcppMatrix(int _dim1, int _dim2) {
00058 dim1 = _dim1;
00059 dim2 = _dim2;
00060 int i,j;
00061 T *m = (T *)R_alloc(dim1*dim2, sizeof(T));
00062 a = (T **)R_alloc(dim1, sizeof(T *));
00063 for (i = 0; i < dim1; i++)
00064 a[i] = m + i*dim2;
00065 for (i=0; i < dim1; i++)
00066 for (j=0; j < dim2; j++)
00067 a[i][j] = 0;
00068 }
00069
00070 template <typename T> int RcppMatrix<T>::getDim1() const {
00071 return dim1;
00072 }
00073
00074 template <typename T> int RcppMatrix<T>::getDim2() const {
00075 return dim2;
00076 }
00077
00078 template <typename T> int RcppMatrix<T>::rows() const {
00079 return dim1;
00080 }
00081
00082 template <typename T> int RcppMatrix<T>::cols() const {
00083 return dim2;
00084 }
00085
00086 template <typename T>
00087 T& RcppMatrix<T>::operator()(int i, int j) const {
00088 if (i < 0 || i >= dim1 || j < 0 || j >= dim2) {
00089 std::ostringstream oss;
00090 oss << "RcppMatrix: subscripts out of range: " << i << ", " << j;
00091 throw std::range_error(oss.str());
00092 }
00093 return a[i][j];
00094 }
00095
00096 template <typename T>
00097 T **RcppMatrix<T>::cMatrix() {
00098 int i,j;
00099 T *m = (T *)R_alloc(dim1*dim2, sizeof(T));
00100 T **tmp = (T **)R_alloc(dim1, sizeof(T *));
00101 for (i = 0; i < dim1; i++)
00102 tmp[i] = m + i*dim2;
00103 for (i=0; i < dim1; i++)
00104 for (j=0; j < dim2; j++)
00105 tmp[i][j] = a[i][j];
00106 return tmp;
00107 }
00108
00109 template <typename T>
00110 std::vector<std::vector<T> > RcppMatrix<T>::stlMatrix() {
00111 int i,j;
00112 std::vector<std::vector<T> > temp;
00113 for (i = 0; i < dim1; i++) {
00114 temp.push_back(std::vector<T>(dim2));
00115 }
00116 for (i = 0; i < dim1; i++)
00117 for (j = 0; j < dim2; j++)
00118 temp[i][j] = a[i][j];
00119 return temp;
00120 }
00121
00122
00123 template class RcppMatrix<int>;
00124 template class RcppMatrix<double>;
00125