summaryrefslogtreecommitdiffhomepage
path: root/opentrack/simple-mat.hpp
blob: b36b21baa15f1a68ba8c1a91c2569979741c0d84 (plain)
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
#pragma once
#include <initializer_list>

template<typename num, int h, int w>
struct Mat
{
    num data[h][w];

    template<int p>
    Mat<num, w, p> operator*(const Mat<num, w, p>& other) const
    {
        Mat<num, w, p> ret;
        for (int j = 0; j < w; j++)
            for (int i = 0; i < p; i++)
            {
                num sum = num(0);

                for (int k = 0; k < h; k++)
                    sum += data[j][k]*other.data[k][i];

                ret.data[j][i] = sum;
            }

        return ret;
    }

    num operator()(int j, int i) const { return data[j][i]; }
    num& operator()(int j, int i) { return data[j][i]; }

    Mat(std::initializer_list<num>&& list)
    {
        auto iter = list.begin();
        for (int i = 0; i < h; i++)
            for (int j = 0; j < w; j++)
                data[i][j] = *iter++;
    }

    Mat()
    {
        for (int j = 0; j < h; j++)
            for (int i = 0; i < w; i++)
                data[j][i] = 0;
    }

    Mat(const num* mem)
    {
        for (int j = 0; j < h; j++)
            for (int i = 0; i < w; i++)
                data[j][i] = mem[i*h+j];
    }

    // XXX add more operators as needed, third-party dependencies mostly
    // not needed merely for matrix algebra -sh 20141030

    static Mat<num, h, h> eye()
    {
        Mat<num, h, h> ret;
        for (int j = 0; j < h; j++)
            for (int i = 0; i < w; i++)
                ret.data[j][i] = 0;

        for (int i = 0; i < h; i++)
            ret.data[i][i] = 1;

        return ret;
    }

    Mat<num, w, h> t()
    {
        Mat<num, w, h> ret;

        for (int j = 0; j < h; j++)
            for (int i = 0; i < w; i++)
                ret.data[i][j] = data[j][i];

        return ret;
    }
};

template<int h, int w> using dmat = Mat<double, h, w>;