The OpenD Programming Language

1 /++
2 This is a submodule of $(MREF mir,ndslice).
3 
4 Initialisation routines.
5 
6 License: $(HTTP www.apache.org/licenses/LICENSE-2.0, Apache-2.0)
7 Copyright: 2020 Ilia Ki, Kaleidic Associates Advisory Limited, Symmetry Investments
8 Authors: Ilia Ki
9 
10 Macros:
11 SUBREF = $(REF_ALTTEXT $(TT $2), $2, mir, ndslice, $1)$(NBSP)
12 T2=$(TR $(TDNW $(LREF $1)) $(TD $+))
13 +/
14 module mir.ndslice.filling;
15 
16 import mir.ndslice.slice: Slice, SliceKind;
17 
18 /++
19 Fills a matrix with the terms of a geometric progression in each row.
20 Params:
21     matrix = `m × n` matrix to fill
22     vec = vector of progression coefficients length of `m`
23 See_also: $(LINK2 https://en.wikipedia.org/wiki/Vandermonde_matrix, Vandermonde matrix)
24 +/
25 void fillVandermonde(F, SliceKind matrixKind, SliceKind kind)(Slice!(F*, 2, matrixKind) matrix, Slice!(const(F)*, 1, kind) vec)
26 in {
27     assert(matrix.length == vec.length);
28 }
29 do {
30     import mir.conv: to;
31 
32     foreach (v; matrix)
33     {
34         F a = vec.front;
35         vec.popFront;
36         F x = to!F(1);
37         foreach (ref e; v)
38         {
39             e = x;
40             x *= a;
41         }
42     }
43 }
44 
45 ///
46 @safe pure nothrow version(mir_ndslice_test) unittest
47 {
48     import mir.ndslice.slice: sliced;
49     import mir.ndslice.allocation: uninitSlice;
50     auto x = [1.0, 2, 3, 4, 5].sliced;
51     auto v = uninitSlice!double(x.length, x.length);
52     v.fillVandermonde(x);
53     assert(v ==
54         [[  1.0,   1,   1,   1,   1],
55          [  1.0,   2,   4,   8,  16],
56          [  1.0,   3,   9,  27,  81],
57          [  1.0,   4,  16,  64, 256],
58          [  1.0,   5,  25, 125, 625]]);
59 }