-
Notifications
You must be signed in to change notification settings - Fork 5
/
Sparse_matrix.h
138 lines (108 loc) · 2.52 KB
/
Sparse_matrix.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#ifndef SPARSE_MATRIX_H
#define SPARSE_MATRIX_H
#include <math.h>
#include <cstdlib>
#include <stdio.h>
#include <iostream>
enum SparseMatrixOutputType{RCVLIST, FULLMATRIX};
class SparseMatrix
{
public:
SparseMatrix(){rows = 0; cols = 0; colptr = NULL; rowind = NULL; vals = NULL;}
SparseMatrix(int rows, int columns, double *Vals, int *RowInds, int *ColPtr);
~SparseMatrix();
void destructor();
// Returns the element at this row and column.
double operator ()(int row, int column) const;
// Return the transpose of the sparse matrix.
SparseMatrix* transpose() const;
// Return the product of two sparse matrix.
SparseMatrix* Multiply(const SparseMatrix& mat) const;
// Return a mean vector
double* Mean(const unsigned int& num_tree);
// Multiply a sparse matrix with a column vector
double* Multiply_vec(const double* vec) const;
// added by WH
void OutputSparseMatrix(std::ostream &output, SparseMatrixOutputType smtype);
// // add by MM
// void OutputSparseMatrix2(std::ostream &output, SparseMatrixOutputType smtype);
private:
int rows;
int cols;
int* colptr; // length cols + 1
int* rowind; // length = number of entries = colptr[cols]
double* vals; // length = number of entries = colptr[cols]
SparseMatrix(int rows, int columns, int nnz)
{
this->rows = rows;
cols = columns;
vals = new double[nnz];
colptr = new int[cols + 1];
rowind = new int[nnz];
}
SparseMatrix(int rows, int columns)
{
this->rows = rows;
cols = columns;
vals = NULL;
rowind = NULL;
colptr = new int[cols + 1];
}
inline void setNNZ(int nnz)
{
vals = new double[nnz];
rowind = new int[nnz];
}
template <typename T>
class Vector
{
public:
inline Vector(int initialSize)
{
allocated = initialSize;
count = 0;
values = new T[allocated];
}
inline ~Vector()
{
delete[] values;
}
void add(const T& elem)
{
if (count == allocated)
{
T *temp = new T[allocated];
for (int i = 0; i < allocated; i++)
{
temp[i] = values[i];
}
delete[] values;
values = new T[allocated * 2];
for (int i = 0; i < allocated; i++)
{
values[i] = temp[i];
}
delete[] temp;
allocated *= 2;
}
values[count++] = elem;
}
inline const T& operator[] (int index) const
{
return values[index];
}
inline T& operator[] (int index)
{
return values[index];
}
inline int size() const
{
return count;
}
private:
T *values;
int count;
int allocated;
};
};
#endif // SPARSE_MATRIX_H