aboutsummaryrefslogtreecommitdiff
path: root/sys/libmath/linalg.c
blob: 09e100cf6ea83f782848ceefd07f363ddea0f584 (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
#include <u.h>
#include <libn.h>
#include <libmath.h>

// -----------------------------------------------------------------------
// Vector

void
linalg·normalize(math·Vector vec)
{
    double norm;

    norm = blas·norm(vec.len, vec.data, 1);
    blas·scale(vec.len, 1/norm, vec.data, 1);
}
// TODO: Write blas wrappers that eat vectors for convenience

// -----------------------------------------------------------------------
// Matrix
//
// NOTE: all matrices are row major oriented

/*
 * linalg·lq
 * computes the LQ decomposition of matrix M: M = LQ
 * L is lower triangular
 * Q is orthogonal -> transp(Q) * Q = I
 *
 * m: matrix to factorize. changes in place
 *     + lower triangle -> L
 *     + upper triangle -> all reflection vectors stored in rows
 * w: working buffer: len = ncols!
 */
error
linalg·lq(math·Matrix m, math·Vector w)
{
    int i, j, len;
    double *row, mag;
    enum {
        err·nil,
        err·baddims,
    };

    if (m.dim[0] > m.dim[1]) {
        return err·baddims;
    }

    for (i = 0; i < m.dim[0]; i++, m.data += m.dim[1]) {
        row = m.data   + i;
        len = m.dim[0] - i;

        // TODO: Don't want to compute norm twice!!
        w.data[0] = math·sgn(row[0]) * blas·norm(len, row, 1);
        blas·axpy(len, 1.0, row, 1, w.data, 1);
        mag  = blas·norm(len, w.data, 1);
        blas·scale(len, 1/mag, w.data, 1);

        blas·copy(len - m.dim[0], w.data, 1, m.data + i, 1);
    }

    return err·nil;
}