-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.hpp
executable file
·3022 lines (2577 loc) · 98.1 KB
/
matrix.hpp
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
/// \file matrix.hpp
/* MIT License
*
* Copyright (c) 2024 gc1905
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef __MATRIX_HPP__
#define __MATRIX_HPP__
#include <ostream>
#include <complex>
#include <vector>
#include <initializer_list>
#include <limits>
#include <functional>
#include <algorithm>
namespace Mtx {
template<typename T> class Matrix;
template<class T> struct is_complex : std::false_type {};
template<class T> struct is_complex<std::complex<T>> : std::true_type {};
/** \brief Complex conjugate helper.
*
* Helper function to allow for generalization of code for complex and real types. <br>
* For real numbers, this function returns the input argument unchanged. <br>
* For complex numbers, this function calls std::conj.
*/
template<typename T, typename std::enable_if<!is_complex<T>::value,int>::type = 0>
inline T cconj(T x) {
return x;
}
template<typename T, typename std::enable_if<is_complex<T>::value,int>::type = 0>
inline T cconj(T x) {
return std::conj(x);
}
/** \brief Complex sign helper.
*
* Helper function to allow for generalization of code for complex and real types. <br>
* For real numbers, this function returns sign bit, i.e., 1 when the value is non-negative and -1 otherwise. <br>
* For complex numbers, this function calculates \f$ e ^ {i \cdot arg(x)} \f$.
*/
template<typename T, typename std::enable_if<!is_complex<T>::value,int>::type = 0>
inline T csign(T x) {
return (x > static_cast<T>(0)) ? static_cast<T>(1) : static_cast<T>(-1);
}
template<typename T, typename std::enable_if<is_complex<T>::value,int>::type = 0>
inline T csign(T x) {
auto x_arg = std::arg(x);
T y(0, x_arg);
return std::exp(y);
}
/** \brief Singular matrix exception.
*
* This exception is thrown by functions like matrix inversion or factorization that are defined to operate on non-singular
* matrices when singular matrix is provided as an input.
*
* @see std::domain_error
*/
class singular_matrix_exception : public std::domain_error {
public:
singular_matrix_exception(const std::string& message) : std::domain_error(message) {}
};
/** \brief Result of LU decomposition.
*
* This structure stores the result of LU decomposition, returned by lu() function.
*/
template<typename T>
struct LU_result {
/**\brief Lower triangular matrix
*/
Matrix<T> L;
/**\brief Upper triangular matrix
*/
Matrix<T> U;
};
/** \brief Result of LU decomposition with pivoting.
*
* This structure stores the result of LU decomposition with pivoting, returned by lup() function.
*/
template<typename T>
struct LUP_result {
/**\brief Lower triangular matrix
*/
Matrix<T> L;
/**\brief Upper triangular matrix
*/
Matrix<T> U;
/**\brief Vector with column permutation indices
*/
std::vector<unsigned> P;
};
/** \brief Result of QR decomposition.
*
* This structure stores the result of QR decomposition, returned by, e.g., from qr() function.
* Note that the dimensions of \a Q and \a R matrices depends on the employed variant of QR decomposition.
*/
template<typename T>
struct QR_result {
/**\brief Orthogonal matrix
*/
Matrix<T> Q;
/**\brief Upper triangular matrix
*/
Matrix<T> R;
};
/** \brief Result of Hessenberg decomposition.
*
* This structure stores the result of the Hessenberg decomposition, returned by hessenberg() function.
*/
template<typename T>
struct Hessenberg_result {
/**\brief Matrix with upper Hessenberg form
*/
Matrix<T> H;
/**\brief Orthogonal matrix
*/
Matrix<T> Q;
};
/** \brief Result of LDL decomposition.
*
* This structure stores the result of LDL decomposition, returned by ldl() function.
*/
template<typename T>
struct LDL_result {
/**\brief Lower triangular matrix
*/
Matrix<T> L;
/**\brief Vector with diagonal elements of diagonal matrix \a D
*/
std::vector<T> d;
};
/** \brief Result of eigenvalues.
*
* This structure stores the result of matrix eigenvalue calculation, returned by eigenvalues() function.
*/
template<typename T>
struct Eigenvalues_result {
/**\brief Vector of eigenvalues.
*/
std::vector<std::complex<T>> eig;
/**\brief Indicates if the eigenvalue algorithm has converged to assumed precision.
*/
bool converged;
/**\brief Error of eigenvalue calculation after the last iteration.
*/
T err;
};
/** \brief Matrix of zeros.
*
* Create a matrix of size \a nrows x \a ncols and fill it with all elements set to 0.
* \param nrows number of rows (the first dimension)
* \param ncols number of columns (the second dimension)
* \return zeros matrix
*/
template<typename T>
inline Matrix<T> zeros(unsigned nrows, unsigned ncols) {
return Matrix<T>(static_cast<T>(0), nrows, ncols);
}
/** \brief Square matrix of zeros.
*
* Construct a square matrix of size \a n x \a n and fill it with all elements set to 0.
* \param n size of the square matrix (the first and the second dimension)
* \return zeros matrix
*/
template<typename T>
inline Matrix<T> zeros(unsigned n) {
return zeros<T>(n,n);
}
/** \brief Matrix of ones.
*
* Construct a matrix of size \a nrows x \a ncols and fill it with all elements set to 1. <br>
* In case of complex data types, matrix is filled with \f$1 + 0i\f$.
* \param nrows number of rows (the first dimension)
* \param ncols number of columns (the second dimension)
* \return ones matrix
*/
template<typename T>
inline Matrix<T> ones(unsigned nrows, unsigned ncols) {
return Matrix<T>(static_cast<T>(1), nrows, ncols);
}
/** \brief Square matrix of ones.
*
* Construct a square matrix of size \a n x \a n and fill it with all elements set to 1. <br>
* In case of complex datatype, matrix is filled with \f$1 + 0i\f$.
* \param n size of the square matrix (the first and the second dimension)
* \return zeros matrix
*/
template<typename T>
inline Matrix<T> ones(unsigned n) {
return ones<T>(n,n);
}
/** \brief Identity matrix.
*
* Construct a square identity matrix.
* In case of complex datatype, the diagonal elements are set to \f$1 + 0i\f$.
* \param n size of the square matrix (the first and the second dimension)
* \return zeros matrix
*/
template<typename T>
Matrix<T> eye(unsigned n) {
Matrix<T> A(static_cast<T>(0), n, n);
for (unsigned i = 0; i < n; i++)
A(i,i) = static_cast<T>(1);
return A;
}
/** \brief Diagonal matrix from array.
*
* Constructs a diagonal matrix of size \a n x \a n, whose diagonal elements are set to the elements stored in the \a array.
* \param array pointer to the first element of the array where the diagonal elements are stored
* \param n size of the matrix to be constructed. Also, a number of elements stored in \a array
* \return diagonal matrix
*/
template<typename T>
Matrix<T> diag(const T* array, size_t n) {
Matrix<T> A(static_cast<T>(0), n, n);
for (unsigned i = 0; i < n; i++) {
A(i,i) = array[i];
}
return A;
}
/** \brief Diagonal matrix from std::vector.
*
* Constructs a diagonal matrix, whose diagonal elements are set to the elements stored in the std::vector \a v. Size of the
* matrix is equal to the vector size.
* \param v vector of diagonal elements
* \return diagonal matrix
*/
template<typename T>
inline Matrix<T> diag(const std::vector<T>& v) {
return diag(v.data(), v.size());
}
/** \brief Diagonal extraction.
*
* Store diagonal elements of a square matrix in std::vector.
* \param A square matrix
* \return vector of diagonal elements
*
* \throws std::runtime_error when the input matrix is not square
*/
template<typename T>
std::vector<T> diag(const Matrix<T>& A) {
if (! A.issquare()) throw std::runtime_error("Input matrix is not square");
std::vector<T> v;
v.resize(A.rows());
for (unsigned i = 0; i < A.rows(); i++)
v[i] = A(i,i);
return v;
}
/** \brief Circulant matrix from array.
*
* Constructs a circulant matrix of size \a n x \a n by taking the elements from \a array as the first column.
* \param array pointer to the first element of the array where the elements of the first column are stored
* \param n size of the matrix to be constructed. Also, a number of elements stored in \a array
* \return circulant matrix
*/
template<typename T>
Matrix<T> circulant(const T* array, unsigned n) {
Matrix<T> A(n, n);
for (unsigned j = 0; j < n; j++)
for (unsigned i = 0; i < n; i++)
A((i+j) % n,j) = array[i];
return A;
}
/** \brief Create complex matrix from real and imaginary matrices.
*
* Constructs a matrix of std::complex type from real matrices providing real and imaginary parts.
* \a Re and \a Im matrices must have the same dimensions.
* \param Re real part matrix
* \param Im imaginary part matrix
* \return complex matrix with real part set to \a Re and imaginary part to \a Im
*
* \throws std::runtime_error when \a Re and \a Im have different dimensions
*/
template<typename T>
Matrix<std::complex<T>> make_complex(const Matrix<T>& Re, const Matrix<T>& Im) {
if (Re.rows() != Im.rows() || Re.cols() != Im.cols()) throw std::runtime_error("Size of input matrices does not match");
Matrix<std::complex<T> > C(Re.rows(),Re.cols());
for (unsigned n = 0; n < Re.numel(); n++) {
C(n).real(Re(n));
C(n).imag(Im(n));
}
return C;
}
/** \brief Create complex matrix from real matrix.
*
* Constructs a matrix of std::complex type from real and imaginary matrices.
* \param Re real part matrix
* \return complex matrix with real part set to \a Re and imaginary part to zero
*/
template<typename T>
Matrix<std::complex<T>> make_complex(const Matrix<T>& Re) {
Matrix<std::complex<T>> C(Re.rows(),Re.cols());
for (unsigned n = 0; n < Re.numel(); n++) {
C(n).real(Re(n));
C(n).imag(static_cast<T>(0));
}
return C;
}
/** \brief Get real part of complex matrix.
*
* Constructs a matrix of real type from std::complex matrix by taking its real part.
*/
template<typename T>
Matrix<T> real(const Matrix<std::complex<T>>& C) {
Matrix<T> Re(C.rows(),C.cols());
for (unsigned n = 0; n < C.numel(); n++)
Re(n) = C(n).real();
return Re;
}
/** \brief Get imaginary part of complex matrix.
*
* Constructs a matrix of real type from std::complex matrix by taking its imaginary part.
*/
template<typename T>
Matrix<T> imag(const Matrix<std::complex<T>>& C) {
Matrix<T> Re(C.rows(),C.cols());
for (unsigned n = 0; n < C.numel(); n++)
Re(n) = C(n).imag();
return Re;
}
/** \brief Circulant matrix from std::vector.
*
* Constructs a circulant matrix, whose the elements of the first column are set to the elements stored in the std::vector \a v. Size of the
* matrix is equal to the vector size.
* \param v vector with data
* \return circulant matrix
*/
template<typename T>
inline Matrix<T> circulant(const std::vector<T>& v) {
return circulant(v.data(), v.size());
}
/** \brief Transpose a matrix.
*
* Returns a matrix that is a transposition of an input matrix.
*/
template<typename T>
inline Matrix<T> transpose(const Matrix<T>& A) {
return A.transpose();
}
/** \brief Transpose a complex matrix.
*
* Returns a matrix that is a conjugate (Hermitian) transposition of an input matrix. <br>
* Conjugate transpose applies a conjugate operation to all elements in addition to matrix transposition.
*/
template<typename T>
inline Matrix<T> ctranspose(const Matrix<T>& A) {
return A.ctranspose();
}
/** \brief Circular shift.
*
* Returns a matrix that is created by shifting the columns and rows of an input matrix in a circular manner. <br>
* If the specified shift factor is a positive value, columns of the matrix are shifted towards right or rows are shifted towards bottom.
* A negative value may be used to apply shifts in opposite directions.
* \param A matrix
* \param row_shift row shift factor
* \param col_shift column shift factor
* \return matrix inverse
*/
template<typename T>
Matrix<T> circshift(const Matrix<T>& A, int row_shift, int col_shift) {
Matrix<T> B(A.rows(), A.cols());
for (int i = 0; i < A.rows(); i++) {
int ii = (i + row_shift) % A.rows();
for (int j = 0; j < A.cols(); j++) {
int jj = (j + col_shift) % A.cols();
B(ii,jj) = A(i,j);
}
}
return B;
}
/** \brief Repeat matrix.
*
* Form a block matrix of size \a m by \a n, with a copy of matrix A as each element.
* \param A input matrix to be repeated
* \param m number of times to repeat matrix A in vertical dimension (rows)
* \param n number of times to repeat matrix A in horizontal dimension (columns)
*/
template<typename T>
Matrix<T> repmat(const Matrix<T>& A, unsigned m, unsigned n) {
Matrix<T> B(m * A.rows(), n * A.cols());
for (unsigned cb = 0; cb < n; cb++)
for (unsigned rb = 0; rb < m; rb++)
for (unsigned c = 0; c < A.cols(); c++)
for (unsigned r = 0; r < A.rows(); r++)
B(rb*A.rows() + r, cb*A.cols() + c) = A(r, c);
return B;
}
/** \brief Frobenius norm.
*
* Calculates Frobenius norm of real matrix. <br>
* More information https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm
*/
template<typename T>
double norm_fro(const Matrix<T>& A) {
double sum = 0;
for (unsigned i = 0; i < A.numel(); i++)
sum += A(i) * A(i);
return std::sqrt(sum);
}
/** \brief Frobenius norm of complex matrix.
*
* Calculates Frobenius norm of complex matrix. <br>
* More information: https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm
*/
template<typename T>
double norm_fro(const Matrix<std::complex<T> >& A) {
double sum = 0;
for (unsigned i = 0; i < A.numel(); i++) {
T x = std::abs(A(i));
sum += x * x;
}
return std::sqrt(sum);
}
/** \brief Extract triangular lower part.
*
* Return a new matrix formed by extracting the lower triangular part of the input matrix, and setting all other elements to zero.
*/
template<typename T>
Matrix<T> tril(const Matrix<T>& A) {
Matrix<T> B(A);
for (unsigned row = 0; row < B.rows(); row++)
for (unsigned col = row+1; col < B.cols(); col++)
B(row,col) = 0;
return B;
}
/** \brief Extract triangular upper part.
*
* Return a new matrix formed by extracting the upper triangular part of the input matrix, and setting all other elements to zero.
*/
template<typename T>
Matrix<T> triu(const Matrix<T>& A) {
Matrix<T> B(A);
for (unsigned col = 0; col < B.cols(); col++)
for (unsigned row = col+1; row < B.rows(); row++)
B(row,col) = 0;
return B;
}
/** \brief Lower triangular matrix check.
*
* Return true if A is a lower triangular matrix, i.e., when it has nonzero entries only on the main diagonal and below. This function
* uses hard decision for equality check.
*/
template<typename T>
bool istril(const Matrix<T>& A) {
for (unsigned row = 0; row < A.rows(); row++)
for (unsigned col = row+1; col < A.cols(); col++)
if (A(row,col) != static_cast<T>(0)) return false;
return true;
}
/** \brief Lower triangular matrix check.
*
* Return true if A is a lower triangular matrix, i.e., when it has nonzero entries only on the main diagonal and below. This function
* uses hard decision for equality check.
*/
template<typename T>
bool istriu(const Matrix<T>& A) {
for (unsigned col = 0; col < A.cols(); col++)
for (unsigned row = col+1; row < A.rows(); row++)
if (A(row,col) != static_cast<T>(0)) return false;
return true;
}
/** \brief Hessenberg matrix check.
*
* Return true if A is a, upper Hessenberg matrix, i.e., it is square and has only zero entries below the first subdiagonal. This function
* uses hard decision for equality check.
*/
template<typename T>
bool ishess(const Matrix<T>& A) {
if (!A.issquare())
return false;
for (unsigned row = 2; row < A.rows(); row++)
for (unsigned col = 0; col < row-2; col++)
if (A(row,col) != static_cast<T>(0)) return false;
return true;
}
/** \brief Applies custom function element-wise in-place.
*
* Applies specified function \a func to all elements of the input matrix. <br>
* This function applies operation to the elements in-place (zero-copy). In order to apply the function to the copy of the matrix without
* modifying the input one, use foreach_elem_copy().
* \param A input matrix to be modified
* \param func function to be applied element-wise to A. It inputs one variable of template type T and returns variable of the same type.
*/
template<typename T>
inline void foreach_elem(Matrix<T>& A, std::function<T(T)> func) {
for (unsigned i = 0; i < A.numel(); i++)
A(i) = func(A(i));
}
/** \brief Applies custom function element-wise with matrix copy.
*
* Applies the specified function \a func to all elements of the input matrix. <br>
* This function applies operation to the copy of the input matrix. For in-place (zero-copy) operation, use foreach_elem().
* \param A input matrix
* \param func function to be applied element-wise to A. It inputs one variable of template type T and returns variable of the same type
* \return output matrix whose elements were modified by the function \a func
*/
template<typename T>
inline Matrix<T> foreach_elem_copy(const Matrix<T>& A, std::function<T(T)> func) {
Matrix<T> B(A);
foreach_elem(B, func);
return B;
}
/** \brief Permute rows of the matrix.
*
* Creates a copy of the matrix with permutation of rows specified as input parameter. Each row in the new matrix is a copy of respective
* row from the input matrix indexed by permutation vector.
* The size of the output matrix is \a perm.size() x \a A.cols(). <br>
* \param A input matrix
* \param perm permutation vector with row indices
* \return output matrix created by row permutation of \a A
*
* \throws std::runtime_error when permutation vector is empty
* \throws std::out_of_range when any index in permutation vector is out of range
*/
template<typename T>
Matrix<T> permute_rows(const Matrix<T>& A, const std::vector<unsigned> perm) {
if (perm.empty()) throw std::runtime_error("Permutation vector is empty");
Matrix<T> B(perm.size(), A.cols());
for (unsigned p = 0; p < perm.size(); p++) {
if (!(perm[p] < A.rows())) throw std::out_of_range("Index in permutation vector out of range");
for (unsigned c = 0; c < A.cols(); c++)
B(p,c) = A(perm[p],c);
}
return B;
}
/** \brief Permute columns of the matrix.
*
* Creates a copy of the matrix with permutation of columns specified as input parameter. Each column in the new matrix is a copy of respective
* column from the input matrix indexed by permutation vector.
* The size of the output matrix is \a A.rows() x \a perm.size(). <br>
* \param A input matrix
* \param perm permutation vector with column indices
* \return output matrix created by column permutation of \a A
*
* \throws std::runtime_error when permutation vector is empty
* \throws std::out_of_range when any index in permutation vector is out of range
*/
template<typename T>
Matrix<T> permute_cols(const Matrix<T>& A, const std::vector<unsigned> perm) {
if (perm.empty()) throw std::runtime_error("Permutation vector is empty");
Matrix<T> B(A.rows(), perm.size());
for (unsigned p = 0; p < perm.size(); p++) {
if (!(perm[p] < A.cols())) throw std::out_of_range("Index in permutation vector out of range");
for (unsigned r = 0; r < A.rows(); r++)
B(r,p) = A(r,perm[p]);
}
return B;
}
/** \brief Matrix multiplication.
*
* Performs multiplication of two matrices.
*
* This function supports template parameterization of input matrix transposition, providing better efficiency than in case of using
* ctranspose() function due to zero-copy operation. In case of complex matrices, conjugate (Hermitian) transpose is used.
*
* \tparam transpose_first if set to true, the left-side input matrix will be transposed during operation
* \tparam transpose_second if set to true, the right-side input matrix will be transposed during operation
*
* \param A left-side matrix of size \a N x \a M (after transposition)
* \param B right-side matrix of size \a M x \a K (after transposition)
* \return output matrix of size \a N x \a K
*/
template<typename T, bool transpose_first = false, bool transpose_second = false>
Matrix<T> mult(const Matrix<T>& A, const Matrix<T>& B) {
// Adjust dimensions based on transpositions
unsigned rows_A = transpose_first ? A.cols() : A.rows();
unsigned cols_A = transpose_first ? A.rows() : A.cols();
unsigned rows_B = transpose_second ? B.cols() : B.rows();
unsigned cols_B = transpose_second ? B.rows() : B.cols();
if (cols_A != rows_B) throw std::runtime_error("Unmatching matrix dimensions for mult");
Matrix<T> C(static_cast<T>(0), rows_A, cols_B);
for (unsigned i = 0; i < rows_A; i++)
for (unsigned j = 0; j < cols_B; j++)
for (unsigned k = 0; k < cols_A; k++)
C(i,j) += (transpose_first ? cconj(A(k,i)) : A(i,k)) *
(transpose_second ? cconj(B(j,k)) : B(k,j));
return C;
}
/** \brief Matrix Hadamard (elementwise) multiplication.
*
* Performs Hadamard (elementwise) multiplication of two matrices.
*
* This function supports template parameterization of input matrix transposition, providing better efficiency than in case of using
* ctranspose() function due to zero-copy operation. In case of complex matrices, conjugate (Hermitian) transpose is used.
*
* \tparam transpose_first if set to true, the left-side input matrix will be transposed during operation
* \tparam transpose_second if set to true, the right-side input matrix will be transposed during operation
*
* \param A left-side matrix of size \a N x \a M (after transposition)
* \param B right-side matrix of size \a N x \a M (after transposition)
* \return output matrix of size \a N x \a M
*/
template<typename T, bool transpose_first = false, bool transpose_second = false>
Matrix<T> mult_hadamard(const Matrix<T>& A, const Matrix<T>& B) {
// Adjust dimensions based on transpositions
unsigned rows_A = transpose_first ? A.cols() : A.rows();
unsigned cols_A = transpose_first ? A.rows() : A.cols();
unsigned rows_B = transpose_second ? B.cols() : B.rows();
unsigned cols_B = transpose_second ? B.rows() : B.cols();
if ((rows_A != rows_B) || (cols_A != cols_B)) throw std::runtime_error("Unmatching matrix dimensions for mult_hadamard");
Matrix<T> C(static_cast<T>(0), rows_A, cols_A);
for (unsigned i = 0; i < rows_A; i++)
for (unsigned j = 0; j < cols_A; j++)
C(i,j) += (transpose_first ? cconj(A(j,i)) : A(i,j)) *
(transpose_second ? cconj(B(j,i)) : B(i,j));
return C;
}
/** \brief Matrix addition.
*
* Performs addition of two matrices.
*
* This function supports template parameterization of input matrix transposition, providing better efficiency than in case of using
* ctranspose() function due to zero-copy operation. In case of complex matrices, conjugate (Hermitian) transpose is used.
*
* \tparam transpose_first if set to true, the left-side input matrix will be transposed during operation
* \tparam transpose_second if set to true, the right-side input matrix will be transposed during operation
*
* \param A left-side matrix of size \a N x \a M (after transposition)
* \param B right-side matrix of size \a N x \a M (after transposition)
* \return output matrix of size \a N x \a M
*/
template<typename T, bool transpose_first = false, bool transpose_second = false>
Matrix<T> add(const Matrix<T>& A, const Matrix<T>& B) {
// Adjust dimensions based on transpositions
unsigned rows_A = transpose_first ? A.cols() : A.rows();
unsigned cols_A = transpose_first ? A.rows() : A.cols();
unsigned rows_B = transpose_second ? B.cols() : B.rows();
unsigned cols_B = transpose_second ? B.rows() : B.cols();
if ((rows_A != rows_B) || (cols_A != cols_B)) throw std::runtime_error("Unmatching matrix dimensions for add");
Matrix<T> C(static_cast<T>(0), rows_A, cols_A);
for (unsigned i = 0; i < rows_A; i++)
for (unsigned j = 0; j < cols_A; j++)
C(i,j) += (transpose_first ? cconj(A(j,i)) : A(i,j)) +
(transpose_second ? cconj(B(j,i)) : B(i,j));
return C;
}
/** \brief Matrix subtraction.
*
* Performs subtraction of two matrices.
*
* This function supports template parameterization of input matrix transposition, providing better efficiency than in case of using
* ctranspose() function due to zero-copy operation. In case of complex matrices, conjugate (Hermitian) transpose is used.
*
* \tparam transpose_first if set to true, the left-side input matrix will be transposed during operation
* \tparam transpose_second if set to true, the right-side input matrix will be transposed during operation
*
* \param A left-side matrix of size \a N x \a M (after transposition)
* \param B right-side matrix of size \a N x \a M (after transposition)
* \return output matrix of size \a N x \a M
*/
template<typename T, bool transpose_first = false, bool transpose_second = false>
Matrix<T> subtract(const Matrix<T>& A, const Matrix<T>& B) {
// Adjust dimensions based on transpositions
unsigned rows_A = transpose_first ? A.cols() : A.rows();
unsigned cols_A = transpose_first ? A.rows() : A.cols();
unsigned rows_B = transpose_second ? B.cols() : B.rows();
unsigned cols_B = transpose_second ? B.rows() : B.cols();
if ((rows_A != rows_B) || (cols_A != cols_B)) throw std::runtime_error("Unmatching matrix dimensions for subtract");
Matrix<T> C(static_cast<T>(0), rows_A, cols_A);
for (unsigned i = 0; i < rows_A; i++)
for (unsigned j = 0; j < cols_A; j++)
C(i,j) += (transpose_first ? cconj(A(j,i)) : A(i,j)) -
(transpose_second ? cconj(B(j,i)) : B(i,j));
return C;
}
/** \brief Multiplication of matrix by std::vector
*
* Performs the right multiplication of a matrix with a column vector represented by std::vector. The result of the operation is also a std::vector.
*
* \param A input matrix of size \a N x \a M
* \param v std::vector of size \a M
* \return std::vector of size \a N being the result of multiplication
*/
template<typename T>
std::vector<T> mult(const Matrix<T>& A, const std::vector<T>& v) {
if (A.cols() != v.size()) throw std::runtime_error("Unmatching matrix dimensions for mult");
std::vector<T> u(A.rows(), static_cast<T>(0));
for (unsigned r = 0; r < A.rows(); r++)
for (unsigned c = 0; c < A.cols(); c++)
u[r] += v[c] * A(r,c);
return u;
}
/** \brief Multiplication of std::vector by matrix
*
* Performs the left multiplication of a std::vector with a matrix. The result of the operation is also a std::vector.
*
* \param v std::vector of size \a N
* \param A input matrix of size \a N x \a M
* \return std::vector of size \a M being the result of multiplication
*/
template<typename T>
std::vector<T> mult(const std::vector<T>& v, const Matrix<T>& A) {
if (A.rows() != v.size()) throw std::runtime_error("Unmatching matrix dimensions for mult");
std::vector<T> u(A.cols(), static_cast<T>(0));
for (unsigned c = 0; c < A.cols(); c++)
for (unsigned r = 0; r < A.rows(); r++)
u[c] += v[r] * A(r,c);
return u;
}
/** \brief Addition of scalar to matrix.
*
* Adds a scalar \f$s\f$ from each element of the input matrix.
* This method does not modify the input matrix but creates a copy.
*/
template<typename T>
Matrix<T> add(const Matrix<T>& A, T s) {
Matrix<T> B(A.rows(), A.cols());
for (unsigned i = 0; i < A.numel(); i++)
B(i) = A(i) + s;
return B;
}
/** \brief Subtraction of scalar from matrix.
*
* Subtracts a scalar \f$s\f$ from each element of the input matrix.
* This method does not modify the input matrix but creates a copy.
*/
template<typename T>
Matrix<T> subtract(const Matrix<T>& A, T s) {
Matrix<T> B(A.rows(), A.cols());
for (unsigned i = 0; i < A.numel(); i++)
B(i) = A(i) - s;
return B;
}
/** \brief Multiplication of matrix by scalar.
*
* Multiplies each element of the input matrix by a scalar \f$s\f$.
* This method does not modify the input matrix but creates a copy.
*/
template<typename T>
Matrix<T> mult(const Matrix<T>& A, T s) {
Matrix<T> B(A.rows(), A.cols());
for (unsigned i = 0; i < A.numel(); i++)
B(i) = A(i) * s;
return B;
}
/** \brief Division of matrix by scalar.
*
* Divides each element of the input matrix by a scalar \f$s\f$.
* This method does not modify the input matrix but creates a copy.
*/
template<typename T>
Matrix<T> div(const Matrix<T>& A, T s) {
Matrix<T> B(A.rows(), A.cols());
for (unsigned i = 0; i < A.numel(); i++)
B(i) = A(i) / s;
return B;
}
/** \brief Matrix ostream operator.
*
* Formats a string incorporating the elements of a matrix. Elements within the same row are separated by space sign ' '.
* Different rows are separated by the endline delimiters.
*/
template<typename T>
std::ostream& operator<<(std::ostream& os, const Matrix<T>& A) {
for (unsigned row = 0; row < A.rows(); row ++) {
for (unsigned col = 0; col < A.cols(); col ++)
os << A(row,col) << " ";
if (row < static_cast<unsigned>(A.rows()-1)) os << std::endl;
}
return os;
}
/** \brief Matrix sum.
*
* Calculates a sum of two matrices \f$ A + B\f$. \f$A\f$ and \f$B\f$ must be the same size.
*/
template<typename T>
inline Matrix<T> operator+(const Matrix<T>& A, const Matrix<T>& B) {
return add(A,B);
}
/** \brief Matrix subtraction.
*
* Calculates a subtraction of two matrices \f$A - B\f$. \f$A\f$ and \f$B\f$ must be the same size.
*/
template<typename T>
inline Matrix<T> operator-(const Matrix<T>& A, const Matrix<T>& B) {
return subtract(A,B);
}
/** \brief Matrix Hadamard product.
*
* Calculates a Hadamard product of two matrices \f$A \otimes B\f$. \f$A\f$ and \f$B\f$ must be the same size.
* Hadamard product is calculated as an element-wise multiplication between the matrices.
*/
template<typename T>
inline Matrix<T> operator^(const Matrix<T>& A, const Matrix<T>& B) {
return mult_hadamard(A,B);
}
/** \brief Matrix product.
*
* Calculates matrix product of two matrices \f$A \cdot B\f$. \f$A\f$ and \f$B\f$ must be the same size.
*/
template<typename T>
inline Matrix<T> operator*(const Matrix<T>& A, const Matrix<T>& B) {
return mult(A,B);
}
/** \brief Matrix and std::vector product.
*
* Calculates product between matrix and std::vector \f$A \cdot v\f$. The input vector is assumed to be a column vector.
*/
template<typename T>
inline std::vector<T> operator*(const Matrix<T>& A, const std::vector<T>& v) {
return mult(A,v);
}
/** \brief std::vector and matrix product.
*
* Calculates product between std::vector and matrix \f$v \cdot A\f$. The input vector is assumed to be a row vector.
*/
template<typename T>
inline std::vector<T> operator*(const std::vector<T>& v, const Matrix<T>& A) {
return mult(v,A);
}
/** \brief Matrix sum with scalar.
*
* Adds a scalar \a s to each element of the matrix.
*/
template<typename T>
inline Matrix<T> operator+(const Matrix<T>& A, T s) {
return add(A,s);
}
/** \brief Matrix subtraction with scalar.
*
* Subtracts a scalar \f$s\f$ from each element of the matrix.
*/
template<typename T>
inline Matrix<T> operator-(const Matrix<T>& A, T s) {
return subtract(A,s);
}
/** \brief Matrix product with scalar.
*
* Multiplies each element of the matrix by a scalar \f$s\f$.
*/
template<typename T>
inline Matrix<T> operator*(const Matrix<T>& A, T s) {
return mult(A,s);
}
/** \brief Matrix division by scalar.
*
* Divides each element of the matrix by a scalar \f$s\f$.
*/
template<typename T>
inline Matrix<T> operator/(const Matrix<T>& A, T s) {
return div(A,s);
}
/** Matrix sum with scalar.
* Adds a scalar \f$s\f$ to each element of the matrix.
*/
template<typename T>
inline Matrix<T> operator+(T s, const Matrix<T>& A) {
return add(A,s);
}
/** \brief Matrix product with scalar.
*
* Multiplies each element of the matrix by a scalar \f$s\f$.
*/
template<typename T>
inline Matrix<T> operator*(T s, const Matrix<T>& A) {
return mult(A,s);
}
/** \brief Matrix sum.
*
* Calculates a sum of two matrices \f$ A + B\f$. \f$A\f$ and \f$B\f$ must be the same size.