source: trunk/TEMPLATES/matrix.h

Last change on this file was 18959, checked in by westram, 3 years ago
File size: 2.0 KB
Line 
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
21template<typename T>
22class symmetric_matrix : virtual Noncopyable {
23    // Symmetrical Matrix (upper triangular matrix)
24
25    size_t     Size;
26    T **m;       // m[i][j]  i <= j !!!!
27
28public:
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
45    ~symmetric_matrix() {
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
Note: See TracBrowser for help on using the repository browser.