ARB
matrix.h
Go to the documentation of this file.
1 // ========================================================= //
2 // //
3 // File : matrix.h //
4 // Purpose : templates for matrices //
5 // //
6 // Coded by Ralf Westram (coder@reallysoft.de) in Jul 20 //
7 // http://www.arb-home.de/ //
8 // //
9 // ========================================================= //
10 
11 #ifndef MATRIX_H
12 #define MATRIX_H
13 
14 #ifndef ARB_ASSERT_H
15 #include <arb_assert.h>
16 #endif
17 #ifndef TRIANGULAR_H
18 #include <triangular.h>
19 #endif
20 
21 template<typename T>
22 class symmetric_matrix : virtual Noncopyable {
23  // Symmetrical Matrix (upper triangular matrix)
24 
25  size_t Size;
26  T **m; // m[i][j] i <= j !!!!
27 
28 public:
29 
30  explicit symmetric_matrix(size_t Size_)
31  : Size(Size_)
32  {
33  const size_t elements = triangular_number(Size);
34  const size_t headsize = Size * sizeof(*m);
35  const size_t datasize = elements * sizeof(*(m[0]));
36 
37  m = (T**)ARB_calloc<char>(headsize+datasize);
38  m[0] = (T*)(((char*)m)+headsize);
39 
40  for (size_t i=1; i<Size; i++) {
41  m[i] = m[i-1]+i;
42  }
43  }
44 
46  free(m);
47  }
48 
49  void set(size_t i, size_t j, T val) { if (i>j) m[i][j] = val; else m[j][i] = val; };
50 
51  T fast_get(size_t i, size_t j) const { arb_assert(i>=j); return m[i][j]; };
52  T get(size_t i, size_t j) const { if (i>j) return m[i][j]; else return m[j][i]; };
53 
54  T get_max_value() const { // O(n*2)
55  // Warning: ignores matrix diagonal
56 
57  T max = m[0][0]; // take any
58  for (size_t i=0; i<Size; i++) {
59  for (size_t j=0; j<i; j++) {
60  if (m[i][j] > max) max = m[i][j];
61  }
62  }
63  return max;
64  }
65 
66  size_t size() const { return Size; }
67 };
68 
69 
70 #else
71 #error matrix.h included twice
72 #endif // MATRIX_H
#define arb_assert(cond)
Definition: arb_assert.h:245
void set(size_t i, size_t j, T val)
Definition: matrix.h:49
T get_max_value() const
Definition: matrix.h:54
CONSTEXPR_INLINE long triangular_number(const long N)
Definition: triangular.h:18
~symmetric_matrix()
Definition: matrix.h:45
size_t size() const
Definition: matrix.h:66
Definition: trnsprob.h:20
symmetric_matrix(size_t Size_)
Definition: matrix.h:30
T fast_get(size_t i, size_t j) const
Definition: matrix.h:51
#define max(a, b)
Definition: f2c.h:154