-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMatrixND.h
2268 lines (2074 loc) · 67.3 KB
/
MatrixND.h
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
//
// Created by Ryan.Zurrin001 on 12/16/2021.
//
#ifndef PHYSICSFORMULA_MATRIXND_H
#define PHYSICSFORMULA_MATRIXND_H
#include <algorithm> // for std::swap
#include <cstddef>
#include <cassert>
#include <vector>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <random>
#include "VectorND.h"
#define THRESHOLD 1e-10
// enum class for different random_device types
enum class RandomGenTypes {
MERSENNE_TWISTER,
LINEAR_CONGRUENTIAL,
KNUTH_B,
MINSTD_RAND,
RANDOM_DEVICE
};
using namespace std;
namespace rez {
// Matrix traits: This describes how a matrix is accessed. By
// externalizing this information into a traits class, the same code
// can be used both with native arrays and matrix classes. To use the
// default implementation of the traits class, a matrix type has to
// provide the following definitions as members:
//
// * typedef ... index_type;
// - The type used for indexing (e.g. size_t)
// * typedef ... value_type;
// - The element type of the matrix (e.g. double)
// * index_type min_row() const;
// - returns the minimal allowed row index
// * index_type max_row() const;
// - returns the maximal allowed row index
// * index_type min_column() const;
// - returns the minimal allowed column index
// * index_type max_column() const;
// - returns the maximal allowed column index
// * value_type& operator()(index_type i, index_type k)
// - returns a reference to the element i,k, where
// min_row() <= i <= max_row()
// min_column() <= k <= max_column()
// * value_type operator()(index_type i, index_type k) const
// - returns the value of element i,k
//
// Note that the functions are all inline and simple, so the compiler
// should completely optimize them away.
template<typename MatrixType>
struct matrix_traits {
typedef typename MatrixType::index_type index_type;
typedef typename MatrixType::value_type value_type;
static index_type min_row(MatrixType const &A) { return A.min_row(); }
static index_type max_row(MatrixType const &A) { return A.max_row(); }
static index_type
min_column(MatrixType const &A) { return A.min_column(); }
static index_type
max_column(MatrixType const &A) { return A.max_column(); }
static value_type &
element(MatrixType &A, index_type i, index_type k) { return A(i, k); }
[[maybe_unused]] static value_type
element(MatrixType const &A, index_type i, index_type k) {
return A(i, k);
}
};
// specialization of the matrix traits for built-in two-dimensional
// arrays
template<typename T, std::size_t rows, std::size_t columns>
struct matrix_traits<T[rows][columns]> {
typedef std::size_t index_type;
typedef T value_type;
static index_type min_row(T const (&)[rows][columns]) { return 0; }
static index_type max_row(T const (&)[rows][columns]) {
return rows - 1;
}
static index_type min_column(T const (&)[rows][columns]) { return 0; }
static index_type max_column(T const (&)[rows][columns]) {
return columns - 1;
}
[[maybe_unused]] static value_type &element(T (&A)[rows][columns],
index_type i,
index_type k) { return A[i][k]; }
[[maybe_unused]] static value_type element(T const (&A)[rows][columns],
index_type i,
index_type k) { return A[i][k]; }
};
// Swap rows i and k of a matrix A
// Note that due to the reference, both dimensions are preserved for
// built-in arrays
template<typename MatrixType>
void swap_rows(MatrixType &A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k) {
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
// check indices
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
std::swap(mt.element(A, i, col), mt.element(A, k, col));
}
// divide row i of matrix A by v
template<typename MatrixType>
void divide_row(MatrixType &A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::value_type v) {
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(v != 0);
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) /= v;
}
// in matrix A, add v times row k to row i
template<typename MatrixType>
void add_multiple_row(MatrixType &A,
typename matrix_traits<MatrixType>::index_type i,
typename matrix_traits<MatrixType>::index_type k,
typename matrix_traits<MatrixType>::value_type v) {
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
assert(mt.min_row(A) <= i);
assert(i <= mt.max_row(A));
assert(mt.min_row(A) <= k);
assert(k <= mt.max_row(A));
for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
mt.element(A, i, col) += v * mt.element(A, k, col);
}
// convert A to reduced row echelon form
template<typename MatrixType>
[[maybe_unused]] void to_reduced_row_echelon_form(MatrixType &A) {
matrix_traits<MatrixType> mt;
typedef typename matrix_traits<MatrixType>::index_type index_type;
index_type lead = mt.min_row(A);
for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row) {
if (lead > mt.max_column(A))
return;
index_type i = row;
while (mt.element(A, i, lead) == 0) {
++i;
if (i > mt.max_row(A)) {
i = row;
++lead;
if (lead > mt.max_column(A))
return;
}
}
swap_rows(A, i, row);
divide_row(A, row, mt.element(A, row, lead));
for (i = mt.min_row(A); i <= mt.max_row(A); ++i) {
if (i != row)
add_multiple_row(A, i, row, -mt.element(A, i, lead));
}
}
}
template<typename MatrixType>
void print_matrix(MatrixType m, int rows, int cols) {
std::cout << right << setprecision(4) << std::endl;
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
std::cout << setw(7) << right << m[r][c] << '\t';
}
std::cout << "\n";
}
std::cout << std::endl;
}
} // namespace rez
//*****************************************************************************
//*****************************************************************************
template<typename T>
class MatrixND
{ // turns a single index into a row and column and returns the value at that index
T getAt(int index);
// sets the value at the given index
void setAt(int index, int value);
public:
int rows{}; // number of rows
int cols{}; // number of columns
std::vector<T> data; // the data
MatrixND(); // default constructor
template<typename ... Args> // constructor with arguments
explicit MatrixND(const int& r_, const int& c_, const T& first, const Args&... args);
MatrixND(int r, int c); // constructor with dimensions
MatrixND(int r, int c, int min, int max, RandomGenTypes type); // constructor with dimensions and random values
MatrixND(std::vector<T>, int rows, int cols); // constructor with data and dimensions
MatrixND(T* data, int rows, int cols); // constructor with data and dimensions
MatrixND(T** data, int rows, int cols); // constructor with data and dimensions
MatrixND(const MatrixND& other); // copy constructor
MatrixND(MatrixND&& other) noexcept; // move constructor
MatrixND& operator=(const MatrixND& other); // copy assignment
MatrixND& operator=(MatrixND&& other) noexcept ; // move assignment
// allow for MatrixND<T> M = {{1,2,3},{4,5,6}} for initializer list
MatrixND(std::initializer_list<std::initializer_list<T>> list) :
MatrixND(list.size(), list.size() ? list.begin()->size() : 0) {
int i = 0, j = 0;
for (auto row : list) {
for (auto elem : row) {
data[i * cols + j] = elem;
j++;
}
i++;
j = 0;
}
}
// set data and dimensions using a vector
void set(std::vector<T>, int rows, int cols);
// set data and dimensions using a pointer
template<typename ... Args>
void set(const T& first, const Args&... args);
// set data at a specific index with a value
void setAt(int row, int col, T value);
// method to swap rows
[[maybe_unused]] void swapRows(int row1, int row2);
// method to swap columns
[[maybe_unused]] void swapCols(int col1, int col2);
// static function to generate and return a random matrix of the given size
// with values between 0 and 1
[[maybe_unused]] static MatrixND<T> random(int rows, int cols);
// static function to generate and return a random matrix of the given size
// with values in the given range
[[maybe_unused]] static MatrixND<T>
random(int rows, int cols, T min, T max, bool continuous = true);
// method to test if matrix is square
[[nodiscard]] bool isSquare() const; // returns true if matrix is square
[[nodiscard]] bool isZero() const; // returns true if matrix is zero
// returns true if matrix is identity
[[maybe_unused]] [[nodiscard]] bool isIdentity() const;
// returns true if matrix is diagonal
[[maybe_unused]] [[nodiscard]] bool isDiagonal() const;
// returns true if matrix is symmetric
[[maybe_unused]] [[nodiscard]] bool isSymmetric() const;
// returns true if matrix is skew symmetric
[[maybe_unused]] [[nodiscard]] bool isSkewSymmetric() const;
// returns true if matrix is upper triangular
[[maybe_unused]] [[nodiscard]] bool isUpperTriangular() const;
// returns true if matrix is lower triangular
[[maybe_unused]] [[nodiscard]] bool isLowerTriangular() const;
// returns true if matrix is tridiagonal
[[maybe_unused]] [[nodiscard]] bool isTridiagonal() const;
//checks if the f1 - f2 close to 0
bool closeEnough(T f1, T f2);
// prints the matrix
void print() const;
// returns the transpose of the matrix
MatrixND<T> transpose();
// returns the inverse of the matrix
MatrixND<T> inverse();
// returns the determinant of the matrix
float determinant();
// function to return the characteristic polynomial of the matrix
std::vector<T> characteristicPolynomial();
// method to create an identity matrix of a square matrix
[[nodiscard]] MatrixND<T> identity();
// method to create an identity matrix of a specified size
[[nodiscard]] static MatrixND<T> identity(int size);
// method to create a zero matrix of a square matrix
MatrixND<T> zero();
static MatrixND<T> zero(int rows, int cols);
// method to calculate the rank of a matrix
int rank();
// method to put matrix into reduced row echelon form
MatrixND<T> rref();
// method to determine if matrix is in reduced row echelon form
bool isRowEchelon();
[[nodiscard]] MatrixND<T> dot(const MatrixND<T> &);
MatrixND<T> cross(const MatrixND<T>&);
MatrixND<T> add(const MatrixND<T> &);
MatrixND<T> sub(const MatrixND<T> &);
MatrixND<T> mult(const MatrixND<T> &);
MatrixND<T> mult(const T &);
// Function to add a multiple of row j to row i (in place).
void addMultiple(int i, int j, T multiple);
bool isEqual(const MatrixND<T> &);
// method to get the cofactorAt matrix of a matrix
MatrixND<T> cofactorMatrix();
// method to calculate the adjoint of a matrix
MatrixND<T> adjoint();
[[nodiscard]] MatrixND<T> concat(const MatrixND<T> &); // concatenate two matrices
[[nodiscard]] MatrixND<T> stack(const MatrixND<T> &); // stack vertically
[[nodiscard]] MatrixND<T> kronecker(const MatrixND<T> &); // kronecker product
// method to find the eigenvectors of the matrix
MatrixND<T> eigenvectors(); // not implemented
// method to return a vector of eigenvalues of the matrix
std::vector<T> eigenvalues(); // not implemented
// method to take the mean of the matrix
double mean();
// method to take the standard deviation of the matrix
double std();
// method to take the covariance of the matrix
double cov();
// method to take the correlation of the matrix
double corr();
// method to take the sum of the matrix elements
double sum();
// encode from row and column to index
[[nodiscard]] int index(int row, int col)const;
[[nodiscard]] int getRows()const; // returns the number of rows
[[nodiscard]] int getCols()const; // returns the number of columns
// find the sub matrix of the given row and column
MatrixND<T> subMatrix(int row, int col);
// method to return the top number of specified r of the matrix
MatrixND<T> topRows(int r);
// method to return the bottom number of specified r of the matrix
MatrixND<T> bottomRows(int r);
// method to return the left number of specified columns of the matrix
MatrixND<T> leftCols(int c);
// method to return the right number of specified columns of the matrix
MatrixND<T> rightCols(int c);
// method to return the top left number of specified r and columns of the matrix
MatrixND<T> topLeft(int r, int c);
// method to return the top right number of specified r and columns of the matrix
MatrixND<T> topRight(int r, int c);
// method to return the bottom left number of specified r and columns of the matrix
MatrixND<T> bottomLeft(int r, int c);
// method to return the bottom right number of specified r and columns of the matrix
MatrixND<T> bottomRight(int r, int c);
// method to return the cofactorAt of the matrix at the specified row and column
T cofactorAt(int row, int col);
// method to return the colwise mean of the matrix
double colwiseMean(int col);
// method to return the rowwise mean of the matrix
double rowwiseMean(int row);
// method to return the colwise standard deviation of the matrix
double colwiseStd(int col);
// method to return the rowwise standard deviation of the matrix
double rowwiseStd(int row);
// method to return the colwise covariance of the matrix
double colwiseCov(int col);
// method to return the rowwise covariance of the matrix
double rowwiseCov(int row);
// method to return the colwise correlation of the matrix
double colwiseCorr(int col);
// method to return the rowwise correlation of the matrix
double rowwiseCorr(int row);
// method to return the colwise sum of the matrix
double colwiseSum(int col);
// method to return the rowwise sum of the matrix
double rowwiseSum(int row);
// method to return the colwise top number of specified r of the matrix
MatrixND<T> colwiseTopRows(int r);
// method to return the rowwise top number of specified r of the matrix
MatrixND<T> rowwiseTopRows(int r);
// method to return the colwise bottom number of specified r of the matrix
MatrixND<T> colwiseBottomRows(int r);
// method to return the rowwise bottom number of specified r of the matrix
MatrixND<T> rowwiseBottomRows(int r);
// colwise to return a colwise vector of the matrix
std::vector<T> colwise(int col);
// look at the data in a colwise fashion
MatrixND<T> colwise();
// rowwise to return a rowwise vector of the matrix
std::vector<T> rowwise(int row);
// look at the data in a rowwise fashion
MatrixND<T> rowwise();
// Function to the find the row with the maximum element at the column given.
// Returns the row index.
int findRowWithMaxElement(int col, int row);
// method to return the max coefficient of the matrix
T max();
// find row with max element
int maxRow();
// find column with max element
int maxCol();
// method to return the min coefficient of the matrix
T min();
// find row with min element
int minRow();
// find column with min element
int minCol();
// method to return the max coefficient of a specified row of the matrix
T maxRow(int row);
// method to return the min coefficient of a specified row of the matrix
T minRow(int row);
// method to return the max coefficient of a specified column of the matrix
T maxCol(int col);
// method to return the min coefficient of a specified column of the matrix
T minCol(int col);
[[nodiscard]] T get(int row, int col)const;
// overload the parenthesis operator to get the value at a given row and column
T& operator()(int row, int col);
// overload the parenthesis operator to set the value at a given row and column
void operator()(int row, int col, T value);
// method to flatten the matrix into a vector
std::vector<T> flatten();
// method to reshape the matrix into a new matrix
MatrixND<T> reshape(int r, int c);
// method to return the diagonal elements of the matrix
MatrixND<T> diag();
// method to return the trace of the matrix
T trace();
// method to return the sum of the absolute values of the matrix
T sumAbs();
// method to turn the matrix into an array
T* array();
MatrixND<T> operator+(const MatrixND<T> &);
VectorND<T> operator+(const VectorND<T> &);
MatrixND<T> operator-(const MatrixND<T> &);
VectorND<T> operator-(const VectorND<T> &);
MatrixND<T> operator*(const MatrixND<T> &);
VectorND<T> operator*(const VectorND<T> &);
MatrixND<T> operator*(const T &);
bool operator==(const MatrixND<T> &);
// template <class U> friend MatrixND<U> operator+ (const MatrixND<U>& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator+ (const U& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator+ (const MatrixND<U>& lhs, U& rhs);
//
// template <class U> friend MatrixND<U> operator- (const MatrixND<U>& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator- (const U& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator- (const MatrixND<U>& lhs, U& rhs);
//
// template <class U> friend MatrixND<U> operator* (const MatrixND<U>& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator* (const U& lhs, MatrixND<U>& rhs);
// template <class U> friend MatrixND<U> operator* (const MatrixND<U>& lhs, const U& rhs);
template<typename K>
friend istream& operator>>(istream& is, MatrixND<T>& m);
template <typename K>
friend ostream& operator<<(ostream& os, const MatrixND<T>& rhs);
~MatrixND() = default;
};
#endif //PHYSICSFORMULA_MATRIXND_H
/** Default Constructor
creates an empty matrix
*/
template <typename T>
MatrixND<T>::MatrixND()
{
data.clear();
rows = 0;
cols = 0;
}
template<typename T>
template<typename ...Args>
MatrixND<T>::MatrixND(const int& r_, const int& c_, const T& first, const Args & ...args)
{
data = {first, args...};
rows = r_;
cols = c_;
auto total = rows * cols;
}
template<typename T>
template<typename ...Args>
inline void MatrixND<T>::set(const T& first, const Args & ...args)
{
data.clear();
auto total = rows * cols;
data.push_back(first);
int dummy[] = { 0, (data.push_back(args), 0)... };
(void)dummy;
for (const auto& i : data)
{
if (i <= total)
{
data.push_back(i);
}
}
}
template<typename T>
void MatrixND<T>::setAt(int row, int col, T value) {
if (row < rows && col < cols) {
data[row * cols + col] = value;
}
}
template<typename T>
[[maybe_unused]] void MatrixND<T>::swapRows(int row1, int row2) {
if (row1 < rows && row2 < rows) {
for (int i = 0; i < cols; i++) {
std::swap(data[row1 * cols + i], data[row2 * cols + i]);
}
}
}
template<typename T>
[[maybe_unused]] void MatrixND<T>::swapCols(int col1, int col2) {
if (col1 < cols && col2 < cols) {
for (int i = 0; i < rows; i++) {
std::swap(data[i * cols + col1], data[i * cols + col2]);
}
}
}
template<typename T>
MatrixND<T> MatrixND<T>::random(int rows, int cols) {
MatrixND<T> m(rows, cols);
// seed a random number generator
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m.setAt(i, j, dis(gen));
}
}
return m;
}
template<typename T>
MatrixND<T> MatrixND<T>::random(int rows, int cols, T min, T max, bool continuous) {
MatrixND<T> m(rows, cols);
// seed a random number generator
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(min, max);
if (continuous) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m.setAt(i, j, dis(gen));
}
}
}
else {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m.setAt(i, j, round(dis(gen)));
}
}
}
return m;
}
template<typename T>
bool MatrixND<T>::isSquare() const {
return rows == cols;
}
template<typename T>
bool MatrixND<T>::isZero() const {
for (const auto& i : data)
{
if (i != 0)
{
return false;
}
}
return true;
}
template<typename T>
[[maybe_unused]] bool MatrixND<T>::isIdentity() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i == j && data[i * cols + j] != 1)
return false;
else if (i != j && data[i * cols + j] != 0)
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isDiagonal() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i != j && data[i * cols + j] != 0)
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isSymmetric() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i != j && data[i * cols + j] != data[j * cols + i])
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isSkewSymmetric() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i != j && data[i * cols + j] != -data[j * cols + i])
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isUpperTriangular() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i > j && data[i * cols + j] != 0)
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isLowerTriangular() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i < j && data[i * cols + j] != 0)
return false;
return true;
}
template<typename T>
bool MatrixND<T>::isTridiagonal() const {
if (!isSquare())
return false;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (i == j && data[i * cols + j] != 0)
continue;
else if (i != j && i + 1 == j && data[i * cols + j] != 0)
continue;
else if (i != j && i - 1 == j && data[i * cols + j] != 0)
continue;
else
return false;
return true;
}
template<typename T>
bool MatrixND<T>::closeEnough(T f1, T f2) {
return fabs(f1-f2) < 1e-9;
}
template<typename T>
inline MatrixND<T>::MatrixND(int r, int c)
{
rows = r;
cols = c;
data = vector<T>(r * c);
}
template<typename T>
MatrixND<T>::MatrixND(int r, int c, int min, int max,
RandomGenTypes type) {
rows = r;
cols = c;
data = vector<T>(r * c);
// seed a random number type depending on the type
std::random_device rd;
if (type == RandomGenTypes::MERSENNE_TWISTER) {
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
} else if (type == RandomGenTypes::LINEAR_CONGRUENTIAL) {
std::minstd_rand gen(rd());
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
} else if (type == RandomGenTypes::KNUTH_B) {
std::knuth_b gen(rd());
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
} else if (type == RandomGenTypes::MINSTD_RAND) {
std::minstd_rand gen(rd());
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
} else if (type == RandomGenTypes::RANDOM_DEVICE) {
std::random_device gen;
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
} else {
std::random_device gen;
std::uniform_real_distribution<> dis(min, max);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i * cols + j] = dis(gen);
}
}
}
// else {
// // default to srand with time
// srand(time(NULL));
// for (int i = 0; i < rows; i++) {
// for (int j = 0; j < cols; j++) {
// data[i * cols + j] = (T)rand() / RAND_MAX * (max - min) + min;
// }
// }
// }
}
/** Constructor
creates the matrix as the following:
@params elements the elements of the matrix in Row-major form
numRows the number of rows in the matrix
numCols the number of columns in the matrix
*/
template <typename T>
MatrixND<T>::MatrixND(std::vector<T> elm, int numRows, int numCols)
{
rows = numRows;
cols = numCols;
data.clear();
for(unsigned int i = 0; i < elm.size(); i++) {
data.push_back(elm[i]);
}
}
template<typename T>
MatrixND<T>::MatrixND(T *data, int rows, int cols)
{
this->rows = rows;
this->cols = cols;
this->data = vector<T>(data, data + rows * cols);
}
template<typename T>
MatrixND<T>::MatrixND(T **data, int rows, int cols) {
//use data from the 2d array
this->rows = rows;
this->cols = cols;
this->data = vector<T>(rows * cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
this->data[i * cols + j] = data[i][j];
}
}
}
/** set
resets the matrix to the input
@params elems, - the elems of the matrix in Row-major form
numRows, - the number of rows in the matrix
numCols; - the number of columns in the matrix
@return void; nothing to return
*/
template <typename T>
void MatrixND<T>::set(std::vector<T> elems, int numRows, int numCols)
{
rows = numRows;
cols = numCols;
data.clear();
for(unsigned int i = 0; i < elems.size(); i++) {
data.push_back(elems[i]);
}
}
/** operator+ (add)
lhs + rhs;
elementwise addition of rhs to lhs
@params rhs; the matrix to add
@return matrix; the sum
*/
template <typename T>
MatrixND<T> MatrixND<T>::operator+(const MatrixND<T> & rhs)
{
return this->add(rhs);
}
template<typename T>
VectorND<T> MatrixND<T>::operator+(const VectorND<T> & rhs) {
assert(this->cols == rhs.size() && this->rows == 1);
VectorND<T> result(this->cols);
for (int i = 0; i < this->cols; i++) {
result.setAt(i, this->data[i] + rhs.getAt(i));
}
return result;
}
/** operator- (subtract)
lhs - rhs;
elementwise subtraction of rhs from lhs
@params rhs; the matrix to subtract
@return matrix; the difference
*/
template <typename T>
MatrixND<T> MatrixND<T>::operator-(const MatrixND<T> & rhs)
{
return this->sub(rhs);
}
template<typename T>
VectorND<T> MatrixND<T>::operator-(const VectorND<T> & rhs) {
assert(this->cols == rhs.size() && this->rows == 1);
VectorND<T> result(this->cols);
for (int i = 0; i < this->cols; i++) {
result.setAt(i, this->data[i] - rhs.getAt(i));
}
return result;
}
/** operator(*) Matrix multiplication
lhs * rhs;
calculate A * x = B
@params rhs; the second matrix
@return matrix; the transformed product matrix
*/
template <typename T>
MatrixND<T> MatrixND<T>::operator*(const MatrixND<T> & rhs)
{
return this->mult(rhs);
}
/** operator* (scalar multiplication)
M<T> * T;
calculate scalar product of a matrix
@params rhs; the scalar;
@return matrix; the transformed product matrix
*/
template <typename T>
MatrixND<T> MatrixND<T>::operator*(const T & t)
{
return this->mult(t);
}
//template<class U>
//MatrixND<U> operator+(const MatrixND<U> &lhs, MatrixND<U> &rhs) {
// int numRows = lhs.getRows();
// int numCols = lhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs.getAt(i) + rhs.getAt(i);
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator+(const U &lhs, MatrixND<U> &rhs) {
// int numRows = rhs.getRows();
// int numCols = rhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs + rhs.getAt(i);
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator+(const MatrixND<U> &lhs, U &rhs) {
// int numRows = lhs.getRows();
// int numCols = lhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs.getAt(i) + rhs;
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator-(const MatrixND<U> &lhs, MatrixND<U> &rhs) {
// int numRows = lhs.getRows();
// int numCols = lhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs.getAt(i) - rhs.getAt(i);
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//} //
//template<class U>
//MatrixND<U> operator-(const U& lhs, MatrixND<U>& rhs) {
// int numRows = rhs.getRows();
// int numCols = rhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs - rhs.getAt(i);
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator-(const MatrixND<U>& lhs, U& rhs) {
// int numRows = lhs.getRows();
// int numCols = lhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; i++)
// tempResult[i] = lhs.getAt(i) - rhs;
//
// MatrixND<U> result(numRows, numCols, tempResult);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator*(const MatrixND<U> &lhs, MatrixND<U> &rhs) {
// // Verify the dimensions of the inputs.
// if (lhs.getCols() != rhs.getRows())
// throw std::invalid_argument("Number of columns in matrix must equal number of rows in vector.");
//
// // Setup the vector for the output.
// MatrixND<U> result(lhs.getRows());
//
// // Loop over rows and columns and perform the multiplication operation element-by-element.
// for (int row=0; row<lhs.getRows(); ++row)
// {
// U cumulativeSum = static_cast<U>(0.0);
// for (int col=0; col<lhs.getCols(); ++col)
// {
// cumulativeSum += (lhs.getAt(row, col) * rhs.getAt(col, row));
// }
// result.setAt(row, cumulativeSum);
// }
//
// return result;
//}
//template<class U>
//MatrixND<U> operator*(const U &lhs, MatrixND<U> &rhs) {
// int numRows = rhs.getRows();
// int numCols = rhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i = 0; i < numElements; ++i) {
// tempResult[i] = lhs * rhs.getAt(i);
// }
//
// MatrixND<U> result(tempResult, numRows, numCols);
// delete[] tempResult;
// return result;
//}
//template<class U>
//MatrixND<U> operator*(const MatrixND<U> &lhs, U &rhs) {
// int numRows = lhs.getRows();
// int numCols = lhs.getCols();
// int numElements = numRows * numCols;
// U *tempResult = new U[numElements];
// for (int i=0; i<numElements; ++i)
// tempResult[i] = lhs.getAt(i) * rhs;
//