-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1785 lines (1363 loc) · 37.3 KB
/
main.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
BOOK: Linear Algebra: Theory, Intuition, Code
AUTHOR: Mike X Cohen
WEBSITE: sincxpress.com
******************************************************************************/
#include <iostream>
#include <ranges>
#include <format>
#include <algorithm>
#define ARMA_PRINT_EXCEPTIONS
#include <armadillo>
#include <matplot/matplot.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include "rref.hpp"
using namespace std::complex_literals;
using namespace arma;
namespace plt = matplot;
std::vector<std::vector<double>> mat_to_vector_2d(const mat& A)
{
auto a_row_to_vector = [&](s64 row_index) {return conv_to<std::vector<double>>::from(A.row(row_index));};
auto a_rows_view = regspace<ivec>(0, 1, A.n_rows - 1) | std::views::transform(a_row_to_vector);
return std::vector(a_rows_view.begin(), a_rows_view.end());
}
// https://stackoverflow.com/a/4609795
template <typename T> int signum(T val) { return (T(0) < val) - (val < T(0)); }
void chapter_02()
{
cout << "CHAPTER: Vectors (chapter 2)" << endl << endl;
// Section 2.1, code block 2.2
// creating scalars (numeric variables)
auto aScalar = 4.l;
// Section 2.2, code block 2.4
// create a vector
vec v = { 2, -1 };
// plot it
auto f = plt::figure(true);
f->width(f->width() * 2);
f->height(f->height() * 2);
plt::plot({ 0.,v[0] }, { 0.,v[1] });
plt::axis(plt::square);
plt::axis({ -3.,3.,-3.,3 });
plt::grid(plt::on);
plt::show();
// Section 2.2, code block 2.6
// row vector
rowvec v1 = { 2, 5, 4, 7 };
// column vector
colvec v2 = { 2, 5, 4, 7 };
// Section 2.3, code block 2.8
{
// start with a row vector
rowvec v1 = { 2, 5, 4, 7 };
// transpose to a column vector
auto v2 = v1.t();
}
// Section 2.5, code block 2.10
{
// two vectors
vec v1 = { 2, 5, 4, 7, };
vec v2 = { 4, 1, 0, 2, };
// scalar-multiply and add
vec v3 = 4 * v1 - 2 * v2;
}
// Section 2.9, code block 2.12
{
// the "base" vector
vec v = { 1, 2 };
auto f = plt::figure(true); //clf
f->width(f->width() * 2);
f->height(f->height() * 2);
plt::hold(plt::on);
plt::plot({ 0., v[0] }, { 0., v[1] })->line_width(2);
for (int i = 0; i < 10; ++i)
{
// random scalar
auto s = plt::randn(0, 1);
auto sv = s * v;
// plot that one on top
plt::plot({ 0., sv[0] }, { 0., sv[1] })->line_width(2);
}
plt::grid(plt::on);
plt::axis(plt::square);
plt::axis({ -4., 4., -4., 4. });
plt::show();
}
cout << endl;
// done.
}
void chapter_03()
{
cout << "CHAPTER: Vector Multiplications (chapter 3)" << endl << endl;
// Section 3.1, code block 3.2
// create two vectors
vec v1 = { 2., 5., 4., 7. };
vec v2 = { 4., 1., 0., 2. };
// dot product between them
double dp = dot(v1, v2);
// Section 3.5, code block 3.4
// some scalars
double l1 = 1;
double l2 = 2;
double l3 = -3;
{
// some vectors
rowvec v1 = { 4, 5, 1 };
rowvec v2 = { -4, 0, -4 };
rowvec v3 = { 1, 3, 2 };
// a linear weighted combination
cout << "l1*v1 + l2*v2 + l3*v3 = " << endl << (l1 * v1 + l2 * v2 + l3 * v3) << endl;
}
// Section 3.6, code block 3.6
{
// two column vectors
colvec v1 = { 2, 5, 4, 7 };
rowvec v2 = { 4, 1, 0, 2 };
// outer product
auto op = (v1.t() * v2.t()).eval();
}
// Section 3.7, code block 3.8
{
// two vectors
vec v1 = { 2, 5, 4, 7 };
vec v2 = { 4, 1, 0, 2 };
// Hadamard multiplication
vec v3 = v1 % v2;
}
// Section 3.9, code block 3.10
// a vector
vec v = { 2, 5, 4, 7 };
// its norm
auto vMag = norm(v);
// the unit vector
auto v_unit = v / vMag;
// Section 3.13, code block 3.12
{
// three vectors
vec v1 = { 1, 2, 3, 4, 5 };
vec v2 = { 2, 3, 4, 5, 6 };
vec v3 = { 3, 4, 5, 6, 7 };
// linear weighted combo
vec w = { -1, 3, -2 };
cout << "v1*w(0) + v2*w(1) + v3*w(2) = " << endl << (v1 * w(0) + v2 * w(1) + v3 * w(2)) << endl;
}
// Section 3.13, code block 3.14
{
rowvec v = { 7, 4, -5, 8, 3 };
auto o = ones(size(v));
// average via dot product
cout << "dot(v, o) / v.n_elem = " << (dot(v, o) / v.n_elem) << endl;
}
// Section 3.13, code block 3.16
{
// vector
vec v = { 7, 4, -5, 8, 3 };
// random weighting vector
vec w = randu(size(v));
// weighted dp
auto wAve = dot(v, w / sum(w));
}
cout << endl;
// done.
}
void chapter_05()
{
cout << "CHAPTER: Matrices (chapter 5)" << endl << endl;
// Section 5.4, code block 5.2
// create a matrix of random numbers
mat A = randn(2, 5);
// two ways to transpose
mat At1 = A.t();
mat At2 = trans(A);
// Section 5.5, code block 5.4
// identity matrix
mat I = eye(4, 4);
// ones matrix
mat O = ones(4);
// zeros matrix
mat Z = zeros(4);
// Section 5.5, code block 5.6
// diagonal matrix from a vecot
mat D = diagmat(vec({ 1, 2, 3, 5 }));
// diagonal of a full matrix
mat R = randn(3, 4);
mat d = diagmat(R);
// Section 5.5, code block 5.8
{
// random numbers matrix
mat A = randn(3, 5);
// another random matrix
mat B = randn(3, 4);
// augmented matrix
mat AB = join_rows(A, B);
}
// Section 5.5, code block 5.10
{
// Create a matrix
mat A = randn(5, 5);
// extract the lower triangle
mat L = trimatl(A);
// extract the upper triangle
mat U = trimatu(A);
}
// Section 5.5, code block 5.12
// start from this vector
vec t = regspace(1, 3);
// toeplitz
mat T = toeplitz(t);
// hankel
// H = hankel(t,t([end 1:end-1]));
// Section 5.8, code block 5.14
{
// scalar to shift by
double l = .01;
// identity matrix
mat I = eye(4, 4);
// just some matrix
mat A = randn(4, 4);
// shifted version
mat As = A + l * I;
}
// Section 5.9, code block 5.16
{
// a matrix
mat A = randn(4, 4);
// its trace
auto tr = trace(A);
}
// Section 5.13, code block 5.18
{
// create two matrices
mat A = randn(4, 2);
mat B = randn(4, 2);
// initialize the result
mat C = zeros(2, 2);
// the multiplications
for (auto coli = 0; coli < 2; ++coli) // columns in A
for (auto colj = 0; colj < 2; ++colj) // columns in B
C(coli, colj) = dot(A.col(coli), B.col(colj));
}
// Section 5.13, code block 5.20
{
// a full matrix
mat A = randn(4, 4);
// get the upper-triangle
mat Al = trimatl(A);
// sum it with its transpose
mat S = Al + Al.t();
// Section 5.13, code block 5.22
// empty rectangular matrix
mat D = zeros(4, 8);
// populate its diagonals
for (auto d = 0; d < min(size(D)); ++d)
D(d, d) = d + 1;
}
cout << endl;
// done.
}
void chapter_06()
{
cout << "CHAPTER: Matrix multiplications (chapter 6)" << endl << endl;
// Section 6.1, code block 6.2
// two matrices
mat M1 = randn(4, 3);
mat M2 = randn(3, 5);
// and their product
mat C = M1 * M2;
// Section 6.2, code block 6.4
mat A = randn(2, 2);
mat B = randn(2, 2);
// notice that C1 != C2
mat C1 = A * B;
mat C2 = B * A;
// Section 6.8, code block 6.6
{
// a pair of matrices
mat M1 = randn(4, 3);
mat M2 = randn(4, 3);
// their Hadamard multiplication
cout << "M1 % M2 = " << endl << (M1 % M2) << endl;
}
// Section 6.9, code block 6.8
{
// a small matrix
mat A = { { 1, 2, 3}, {4, 5, 6 } };
// vectorized
cout << "vectorise(A) = " << endl << vectorise(A) << endl;
}
// Section 6.9, code block 6.10
{
mat A = randn(4, 3);
mat B = randn(4, 3);
// the transpose-trace trick for the frobenius dot product
auto f = trace(A.t() * B);
}
// Section 6.10, code block 6.12
{
mat A = randn(4, 3);
cout << "norm(A,\"fro\") = " << norm(A, "fro") << endl;
}
// Section 6.15, code block 6.14
{
// the matrices
mat A = randn(2, 4);
mat B = randn(4, 3);
// initialize
mat C1 = zeros(2, 3);
// loop over (N) columns in A
for (int i = 0; i < size(A, 1); ++i)
C1 = C1 + A.col(i) * B.row(i);
// show equality by subtraction (expect zeros)
cout << "C1 - A*B = " << endl << (C1 - A * B) << endl;
}
// Section 6.15, code block 6.16
{
// create the matrices
mat D = diagmat(regspace(1, 4));
mat A = randn(4, 4);
// two kinds of multiplication
mat C1 = D % A;
mat C2 = D * A;
// they're the same
cout << "diagmat(C1) = " << endl << diagmat(C1) << endl;
cout << "diagmat(C2) = " << endl << diagmat(C2) << endl;
}
// Section 6.15, code block 6.18
{
// the matrix
mat A = diagmat(randu(3, 1));
// the two symmetric matrices
mat C1 = (A.t() + A) / 2;
mat C2 = A.t() * A;
// their equivalence
cout << "C1-sqrt(C2) = " << endl << (C1 - sqrt(C2)) << endl;
}
// Section 6.15, code block 6.20
{
// matrix and vector
auto m = 5;
mat A = randn(m, m);
vec v = randn(m, 1);
// the two sides of the equation
auto LHS = norm(A * v);
auto RHS = norm(A, "fro") * norm(v);
// their difference
cout << "RHS-LHS = " << (RHS - LHS) << endl; // should always be positive
}
cout << endl;
// done.
}
void chapter_07()
{
cout << "CHAPTER: Rank (chapter 7)" << endl << endl;
// Section 7.3, code block 7.2
// a matrix
mat A = randn(3, 6);
// and its rank
cout << "rank(A) = " << rank(A) << endl;
// Section 7.4, code block 7.4
// scalar
auto s = randn();
// matrix
mat M = randn(3, 5);
// their ranks
auto r1 = rank(M);
auto r2 = rank(s * M);
// are the same
cout << "r1 = " << r1 << ", r2 = " << r2 << endl;
// Section 7.10, code block 7.6
// inspect the source code for rank
// edit rank
// Section 7.15, code block 7.8
{
// two random matrices
mat A = randn(9, 2);
mat B = randn(2, 16);
// the rank of their product (assume max possible)
mat C = A * B;
}
// Section 7.15, code block 7.10
// zeros matrix
mat Z = zeros(5, 5);
// tiny noise matrix
mat N = randn(5, 5) * std::numeric_limits<double>::epsilon() * 1e-307;
// add them together
mat ZN = Z + N;
// check their ranks
cout << "rank(Z) = " << rank(Z) << endl; // r=0
cout << "rank(ZN) = " << rank(ZN) << endl; // r=5
// and the matrix norm
cout << "rank(ZN, \"fro\") = " << norm(ZN, "fro") << endl;
cout << endl;
// done.
}
void chapter_08()
{
cout << "CHAPTER: Matrix spaces (chapter 8)" << endl << endl;
// Section 8.7, code block 8.2
mat A = randn(3, 4);
cout << "null(A) = " << endl << null(A) << endl;
// Section 8.15, code block 8.4
{
// create reduced-rank matrices
mat A = randn(4, 3) * randn(3, 4);
mat B = randn(4, 3) * randn(3, 4);
// find a vector in A's nullspace
vec n = null(A);
// zeros vector
cout << "B*A*n = " << endl << (B * A * n) << endl;
// not zeros vector
cout << "A*B*n = " << endl << (A * B * n) << endl;
}
// Section 8.15, code block 8.6
{
// create a rank-9 matrix
mat A = randn(16, 9) * randn(9, 11);
// "right" null space
mat rn = null(A);
// left-null space
mat ln = null(A.t());
// rank of the matrix
auto r = rank(A);
// check the dimensionalities!
cout << "size(rn,2) + r = " << (size(rn, 1) + r) << endl;
cout << "size(ln,2) + r = " << (size(ln, 1) + r) << endl;
}
cout << endl;
// done.
}
void chapter_09()
{
cout << "CHAPTER: Complex numbers (chapter 9)" << endl << endl;
// Section 9.2, code block 9.2
// one way to create a complex number
cx_double z = { 3,4 };
// initialize zeros
cx_mat Z = zeros<cx_mat>(2, 1);
// can simply replace one element with a complex number
Z(0) = 3.0 + 4i;
// Section 9.3, code block 9.4
{
// some random real and imaginary parts
cx_mat r = randi<cx_mat>(1, 3, distr_param(-3, 3));
cx_mat i = randi<cx_mat>(1, 3, distr_param(-3, 3));
// combine into a matrix
cx_mat Z = r + i * 1i;
// its conjugate
cout << "conj(Z) = " << endl << conj(Z) << endl;
}
// Section 9.5, code block 9.6
// a complex vector
cx_vec v = { 0, 1i };
// Hermitian dot product
cout << "dot(v,v) = " << dot(v, v) << endl;
// Section 9.10, code block 9.8
cx_mat U = { {1. + 1i, 1. - 1i}, {1. - 1i, 1. + 1i} };
U *= .5;
// Hermitian
cout << "U'*U = " << endl << U.ht() * U << endl;
// not Hermitian
cout << "transpose(U)*U = " << endl << U.t() * U << endl;
// Section 9.10, code block 9.10
// create a complex matrix
cx_mat A = cx_mat(randn(3, 3), randn(3, 3));
// new matrices by adding and multiplying
cx_mat A1 = A + A.ht();
cx_mat A2 = A * A.ht();
cout << "ishermitian(A1) = " << A1.is_hermitian() << endl; // issymmetric(A1) is false!
cout << "ishermitian(A2) = " << A2.is_hermitian() << endl;
cout << endl;
// done.
}
void chapter_10()
{
cout << "CHAPTER: Systems of equations (chapter 10)" << endl << endl;
// Section 10.3, code block 10.2
// create a matrix
mat A = randn(4, 3);
// take its LU decomposition
mat L, U, P;
lu(L, U, P, A);
// Section 10.5, code block 10.4
{
mat A = randn(2, 4);
// its RREF
cout << "rref(A) = " << endl << mat_to_rref(A) << endl;
}
// Section 10.12, code block 10.6
{
// the matrix
mat A = { { 2, 0, -3}, {3, 1, 4}, { 1, 0, -1} };
// note: column vector!
vec x = { 2, 3, 4 };
// the constants vector
vec b = A * x;
}
// Section 10.12, code block 10.8
// one example
cout << "rref(randn(3,6)) = " << endl << mat_to_rref(randn(3, 6)) << endl;
cout << endl;
// done.
}
void chapter_11()
{
cout << "CHAPTER: Determinant (chapter 11)" << endl << endl;
// Section 11.6, code block 11.2
mat A = randn(3, 3);
cout << "det(A) = " << det(A) << endl;
// Section 11.6, code block 11.4
{
// random matrix and vector
mat A = randi<mat>(4, 4, distr_param(0, 10));
sword b = randi(distr_param(-10, -1));
// show equivalence
cout << "det(b*A) = " << det(b * A) << ", b^4*det(A) = " << (pow(b, 4) * det(A)) << endl;
}
// Section 11.6, code block 11.6
// matrix sizes
ivec ns = regspace<ivec>(3, 1, 30);
// iterations
auto iters = 100;
// initialize results matrix
mat dets = zeros(ns.size(), iters);
// loop over matrix sizes
for (int ni = 0; ni < ns.size(); ++ni)
{
for (int i = 0; i < iters; ++i)
{
// step 1
mat A = randn(ns(ni), ns(ni));
// step 2
A.col(0) = A.col(1);
// step 3
dets(ni, i) = fabs(det(A));
}
}
auto get_log_mean = [&](s64 row_index) {return log(mean(dets.row(row_index)));};
auto log_means_view = regspace<ivec>(0, 1, ns.size() - 1) | std::views::transform(get_log_mean);
auto log_means = std::vector(log_means_view.begin(), log_means_view.end());
// show in a plot
auto f = plt::figure(true); //clf
f->width(f->width() * 2);
f->height(f->height() * 2);
plt::plot(ns, log_means, "s-");
plt::xlabel("Matrix size");
plt::ylabel("Log determinant");
plt::show();
cout << endl;
// done.
}
void chapter_12()
{
cout << "CHAPTER: Matrix inverse (chapter 12)" << endl << endl;
// Section 12.4, code block 12.2
// a square matrix (full-rank!)
mat A = randn(3, 3);
// inverse
mat Ai = inv(A);
// should equal identity
cout << "A*Ai = " << endl << (A * Ai) << endl;
// Section 12.5, code block 12.4
{
// invertible matrix
mat A = randn(3, 3);
// RREF with identity
mat Ar = mat_to_rref(join_rows(A, eye(3, 3))); // RREF
// extract the inverse part
Ar = Ar.cols(3, 5);
// inverse via inv function
mat Ai = inv(A);
// check for equality
cout << "Ar-Ai = " << endl << (Ar - Ai) << endl;
}
// Section 12.7, code block 12.6
{
// tall matrix
mat A = randn(5, 3);
// left inverse
mat Al = inv(A.t() * A) * A.t();
// check for I
cout << "Al*A = " << endl << (Al * A) << endl;
}
// Section 12.8, code block 12.8
{
// make a reduced-rank matrix
mat A = randn(3, 3);
A.row(1) = A.row(0);
// MP pseudoinverse
mat Api = pinv(A);
cout << "Api*A = " << endl << (Api * A) << endl;
}
// Section 12.12, code block 12.10
{
// create matrix
auto m = 4;
mat A = randn(m, m);
mat M = zeros(m, m);
mat G = zeros(m, m);
// compute matrices
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < m; ++j)
{
// select rows/cols
uvec rows(m);
rows.fill(1);
rows[i] = 0;
uvec cols(m);
cols.fill(1);
cols[j] = 0;
// compute M
M(i, j) = det(A.submat(find(rows == 1), find(cols == 1)));
// compute G
G(i, j) = pow(-1, i + j);
}
}
// compute C
mat C = M % G;
// compute A
mat Ainv = C.t() / det(A);
mat AinvI = inv(A);
cout << "AinvI-Ainv = " << endl << (AinvI - Ainv) << endl; //compare against inv()
}
// Section 12.12, code block 12.12
{
// square matrix
mat A = randn(5, 5);
mat Ai = inv(A);
mat Api = pinv(A);
cout << "Ai-Api = " << endl << (Ai - Api) << endl; // test equivalence
// tall matrix
mat T = randn(5, 3);
mat Tl = inv(T.t() * T) * T.t(); // left inv
mat Tpi = pinv(T); // pinv
cout << "Tl-Tpi = " << endl << (Tl - Tpi) << endl; // test equivalance
}
cout << endl;
// done.
}
void chapter_13()
{
cout << "CHAPTER: Projections and orthogonalization (chapter 13)" << endl << endl;
// Section 13.2, code block 13.2
// matrix and vector
mat A = { {1, 2}, {3, 1}, {1, 1} };
colvec b = { 5.5, -3.5, 1.5 };
// short-cut for least-squares solver
cout << "solve(A,b) = " << endl << solve(A, b) << endl;
// Section 13.6, code block 13.4
{
// the matrix
mat A = randn(4, 3);
// its QR decomposition
mat Q, R;
qr(Q, R, A); // add ,"econ" to get economy decomposition
}
// Section 13.11, code block 13.6
{
// sizes
u64 m = 4;
u64 n = 4;
// matrix
mat A = randn(m, n);
// initialize
mat Q = zeros(m, n);
for (u64 i = 0; i < n; ++i) // loop through columns (n)
{
Q.col(i) = A.col(i);
// orthogonalize
colvec a = A.col(i); // convenience
for (u64 j = 0; j < i; ++j)
{
colvec q = Q.col(j); // convenience
Q.col(i) = Q.col(i) - as_scalar(a.t() * q / (q.t() * q)) * q;
}
// normalize
Q.col(i) = Q.col(i) / norm(Q.col(i));
}
cout << "Q' * Q = " << endl << (Q.t() * Q) << endl;
// test against "real" Q matrix
mat Q2, R;
qr(Q2, R, A);
// note the possible sign differences.
cout << "Q - Q2 = " << endl << (Q - Q2) << endl;
// seemingly non-zero columns will be 0 when adding
cout << "Q + Q2 = " << endl << (Q + Q2) << endl;
}
cout << endl;
// done.
}
void chapter_14()
{
cout << "CHAPTER: Least squares (chapter 14)" << endl << endl;
// Section 14.10, code block 14.2
// load the data
mat data;
data.load("widget_data.txt", csv_ascii);
// design matrix
mat X = join_rows(ones(1000, 1), data.cols(0, 1));
// outcome variable
colvec y = data.col(2);
// beta coefficients
colvec beta = solve(X, y);
// scaled coefficients (intercept not scaled)
rowvec betaScaled = beta.t() / stddev(X);
// Section 14.10, code block 14.4
auto f = plt::figure(true);
f->width(f->width() * 3);
f->height(f->height() * 1.5);
plt::tiledlayout(1, 2);
auto ax1 = plt::nexttile();
plt::axis(ax1, plt::square);
plt::title(ax1, "Time variable");
plt::xlabel(ax1, "Time of day");
plt::ylabel(ax1, "Widgets purchased");
auto l1 = plt::scatter(
ax1,
conv_to<std::vector<double>>::from(X.col(1)),
conv_to<std::vector<double>>::from(y)
);
l1->marker_color("k");
l1->marker_style(plt::line_spec::marker_style::circle);
auto ax2 = plt::nexttile();
plt::axis(ax2, plt::square);
plt::title(ax2, "Age variable");
plt::xlabel(ax2, "Age");
plt::ylabel(ax2, "Widgets purchased");
auto l2 = plt::scatter(
ax2,
conv_to<std::vector<double>>::from(X.col(2)),
conv_to<std::vector<double>>::from(y)
);
l2->marker_color("k");
l2->marker_style(plt::line_spec::marker_style::circle);