-
Notifications
You must be signed in to change notification settings - Fork 28
/
CMatrix.h
1280 lines (1230 loc) · 41.1 KB
/
CMatrix.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
/* This file and CMatrix.cpp contain the basic matrix class. The matrix hierarchy is currently very flat and is designed to be a simple (and hopefully efficient) interface to the LAPACK and BLAS libraries.
21/10/2005 More changes from William Baxter. In particular more redundant consts are removed and a symvColColOff is added for offset multiplication. Some bugs are removed (including in sumCol) and casting is made clearer in many places. Also in several places vector<> is now used instead of declaring an array.
20/10/2005 Incorporated William Baxter's changes which allow compilation of files under MSVC. These included a number of bug fixes (such as my embarrassing use of otherwise: rather than default:!). Also included is a new Matrix method addVal, which is a sensible way of adding to an element.*/
#ifndef CMATRIX_H
#define CMATRIX_H
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <vector>
#include "ndlassert.h"
#include "CNdlInterfaces.h"
#include "ndlexceptions.h"
#include "ndlutil.h"
#include "ndlstrutil.h"
#include "lapack.h"
#ifdef _HDF5
#include <hdf5/hdf5_io.hpp> //in mlprojects/branches
#endif
//using namespace std;
// Base matrix class that acts as an interface to LAPACK and BLAS.
class CMatrix : public CMatInterface, public CStreamInterface
{
public:
// The default constructor.
CMatrix()
{
_init();
nrows = 1;
ncols = 1;
symmetric = false;
triangular = false;
memAllocate();
vals[0] = 0;
}
// A constructor for creating a 1x1 CMatrix from a double.
CMatrix(double val)
{
_init();
nrows = 1;
ncols = 1;
symmetric = false;
triangular = false;
memAllocate();
vals[0] = val;
}
// The standard memory allocating constructor for creating a matrix o f size numRows*numCols.
CMatrix(unsigned int numRows, unsigned int numCols) : nrows(numRows), ncols(numCols)
{
_init();
symmetric = false;
triangular = false;
memAllocate();
}
// Constructor which allocates memory and then fills the CMatrix with constant values.
CMatrix(unsigned int numRows, unsigned int numCols, double val) : nrows(numRows), ncols(numCols)
{
_init();
symmetric = false;
triangular = false;
memAllocate();
setVals(val);
}
// Constructor for initialising a CMatrix from a double* array.
CMatrix(unsigned int numRows, unsigned int numCols, double* inVals) : nrows(numRows), ncols(numCols)
{
_init();
symmetric = false;
triangular = false;
memAllocate();
dcopy_(nrows*ncols, inVals, 1, vals, 1);
}
// Constructor for initialising a CMatrix from a double* array for use with SWIG.
CMatrix(double* pythonInVals, int numRows, int numCols) : nrows(numCols), ncols(numRows)
{
BOUNDCHECK(numRows>0);
BOUNDCHECK(numCols>0);
// for numpy storeage --- first copy memory then transpose.
_init();
symmetric = false;
triangular = false;
memAllocate();
dcopy_(nrows*ncols, pythonInVals, 1, vals, 1);
trans();
}
// This was designed for interfacing with SWIG/Python, but for some reason it seems to cause a memory leak.
// Constructor for initialising a CMatrix from rows of double* array.
/* CMatrix(double* inVals, int numRows, int numCols, int* indexVals, int numIndices) : nrows(numIndices), ncols(numCols) */
/* { */
/* _init(); */
/* symmetric = false; */
/* triangular = false; */
/* memAllocate(); */
/* for(unsigned int i=0; i<numIndices; i++) */
/* for(unsigned int j=0; j<ncols; j++) */
/* vals[i+nrows*j] = inVals[indexVals[i]+nrows*j]; */
/* } */
// Constructor for initialising a CMatrix from a double** array.
/* CMatrix(unsigned int numRows, unsigned int numCols, double** inVals) : nrows(numRows), ncols(numCols) */
/* { */
/* _init(); */
/* symmetric = false; */
/* triangular = false; */
/* memAllocate(); */
/* for(unsigned int i=0; i<nrows; i++) */
/* for(unsigned int j=0; j<ncols; j++) */
/* vals[i+nrows*j] = inVals[i][j]; */
/* } */
CMatrix(unsigned int numRows, unsigned int numCols, vector<double>& inVals) : nrows(numRows), ncols(numCols)
{
_init();
DIMENSIONMATCH(numRows*numCols==inVals.size());
symmetric = false;
triangular = false;
memAllocate();
for(unsigned int i=0; i<inVals.size(); i++)
vals[i] = inVals[i];
}
// Constructor for special initialisations such as identity or random matrices.
CMatrix(unsigned int numRows, unsigned int numCols, char type) : nrows(numRows), ncols(numCols)
{
_init();
setSymmetric(false);
setSymmetric(false);
memAllocate();
switch(type) {
case 'I':
// the identity
DIMENSIONMATCH(numRows==numCols);
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++)
if(i==j)
vals[i+nrows*j] = 1.0;
else
vals[i+nrows*j] = 0.0;
setSymmetric(true);
break;
default:
SANITYCHECK(0);
}
}
// Constructor for special initialisations where a value is also passed.
CMatrix(unsigned int numRows, unsigned int numCols, char type, double val) : nrows(numRows), ncols(numCols)
{
_init();
setSymmetric(false);
setSymmetric(false);
memAllocate();
switch(type) {
case 'S':
// a spherical covariance matrix
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++)
if(i==j)
vals[i+nrows*j] = val;
else
vals[i+nrows*j] = 0.0;
setSymmetric(true);
break;
default:
SANITYCHECK(0);
}
}
CMatrix(const CMatrix& A, vector<unsigned int> indices) : nrows(indices.size()), ncols(1), symmetric(false), triangular(false)
{
_init();
memAllocate();
for(unsigned int i =0; i<indices.size(); i++)
{
setVal(A.getVal(indices[i]), i);
}
}
CMatrix(const CMatrix& A,
vector<unsigned int> rowIndices,
vector<unsigned int> colIndices) :
nrows(rowIndices.size()),
ncols(colIndices.size()),
symmetric(false), triangular(false)
{
_init();
memAllocate();
for(unsigned int i =0; i<rowIndices.size(); i++)
{
for(unsigned int j =0; j<colIndices.size(); j++)
{
setVal(A.getVal(rowIndices[i], colIndices[j]), i, j);
}
}
}
// The copy constructor, it performs a deep copy.
CMatrix(const CMatrix& A) : nrows(A.nrows), ncols(A.ncols), symmetric(A.symmetric), triangular(A.triangular)
{
_init();
memAllocate();
copy(A);
}
// The class destructor, it deallocates the memory.
virtual ~CMatrix()
{
memDeAllocate();
}
// Perform a deep copy of the matrix A, resizing if necessary.
void deepCopy(const CMatrix& A)
{
resize(A.nrows, A.ncols);
copy(A);
}
// Get the number of rows in the matrix.
inline unsigned int getRows() const
{
return nrows;
}
// Get the number of columns in the matrix.
inline unsigned int getCols() const
{
return ncols;
}
// Get the number of elements in the matrix (rows*cols).
inline unsigned int getNumElements() const
{
return nrows*ncols;
}
// Return pointer to the raw column-major storage for the matrix
inline double* getVals()
{
return vals;
}
inline const double* getVals() const
{
return vals;
}
vector<double> getVector() const
{
vector<double> valVector;
for(unsigned int i=0; i<getNumElements(); i++)
{
valVector.push_back(vals[i]);
}
return valVector;
}
// Get the matrix element in the ith row and jth column (indexing from 0).
inline double getVal(unsigned int i, unsigned int j) const
{
#ifdef _NDLPYTHON
if(!(i<nrows))
throw std::range_error("getVal: column index out of range, maximum is " + ndlstrutil::itoa(nrows) + " value was " + ndlstrutil::itoa(i));
if(!(j<ncols))
{
throw std::range_error("getVal: column index out of range, maximum is " + ndlstrutil::itoa(ncols) + " value was " + ndlstrutil::itoa(j));
}
#else
BOUNDCHECK(i<nrows);
BOUNDCHECK(j<ncols);
#endif
return vals[i + nrows*j];
}
// Get the ith element from the matrix.
inline double getVal(unsigned int i) const
{
#ifdef _NDLPYTHON
if(!(i<nrows*ncols))
{
throw std::range_error("getVal: matrix index out of range, maximum is " + ndlstrutil::itoa(nrows*ncols) + " value was " + ndlstrutil::itoa(i));
}
#else
BOUNDCHECK(i<nrows*ncols);
#endif
return vals[i];
}
// Set all elements of the matrix to val.
inline void setVals(double val)
{
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] = val;
}
// Set the ith element of the matrix to val.
inline void setVal(double val, unsigned int i)
{
#ifdef _NDLPYTHON
if(i>=nrows*ncols)
throw std::range_error("setVal: matrix index out of range");
#else
BOUNDCHECK(i<nrows*ncols);
#endif
vals[i] = val;
}
// Add val to the ith element of the matrix.
inline void addVal(double val, unsigned int i)
{
#ifdef _NDLPYTHON
if(i>=nrows*ncols)
throw std::range_error("addVal: matrix index out of range");
#else
BOUNDCHECK(i<nrows*ncols);
#endif
vals[i] += val;
}
// Set the matrix element from the ith row and jth column to val.
inline void setVal(double val, unsigned int i, unsigned int j)
{
#ifdef _NDLPYTHON
if(i>=nrows)
throw std::range_error("setVal: row index out of range");
if(j>=ncols)
throw std::range_error("setVal: column index out of range");
#else
BOUNDCHECK(i<nrows);
BOUNDCHECK(j<ncols);
#endif
vals[i + nrows*j] = val;
}
// Add val to the matrix element from the ith row and jth column.
inline void addVal(double val, unsigned int i, unsigned int j)
{
#ifdef _NDLPYTHON
if(i>=nrows)
throw std::range_error("addVal: row index out of range");
if(j>=ncols)
throw std::range_error("addVal: column index out of range");
#else
BOUNDCHECK(i<nrows);
BOUNDCHECK(j<ncols);
#endif
vals[i + nrows*j] += val;
}
bool isAnyNan() const
{
for(unsigned int i=0; i<nrows*ncols; i++)
{
if(isnan(vals[i]))
return true;
}
return false;
}
bool isAnyInf() const
{
for(unsigned int i=0; i<nrows*ncols; i++)
{
if(isinf(vals[i]))
return true;
}
return false;
}
// Returns true if the matrix has the same number of rows as columns.
inline const bool isSquare() const
{
return nrows==ncols;
}
// Returns true if matrix is triangular.
inline const bool isTriangular() const
{
return triangular;
}
// Sets whether or not matrix is triangular.
inline void setTriangular(const bool val)
{
MATRIXPROPERTIES((val && isSquare()) || !val);
triangular=val;
}
// Returns true if the matrix is symmetric.
inline const bool isSymmetric() const
{
return symmetric;
}
// Sets whether or not matrix is symmetric.
inline void setSymmetric(const bool val)
{
MATRIXPROPERTIES((val && isSquare()) || !val);
symmetric=val;
}
// Returns true if the matrix A has the same dimensions as the matrix.
inline const bool dimensionsMatch(const CMatrix& A) const
{
return (nrows==A.nrows && ncols==A.ncols);
}
// Returns true if A has the same number of rows as the matrix.
inline const bool rowsMatch(const CMatrix& A) const
{
return (nrows==A.nrows);
}
// Returns true if A has the same number of columns as the matrix.
inline const bool colsMatch(const CMatrix& A) const
{
return (ncols==A.ncols);
}
// Add the columns of the matrix to this matrix (should have same number of columns).
void sumCol(const CMatrix& A, double alpha, double beta);
// Add the rows of the matrix to this matrix (should have same number of rows).
void sumRow(const CMatrix& A, double alpha, double beta);
// copy the upper part to the lower or vice versa.
void copySymmetric(const char* type);
void copyRowRow(unsigned int i, const CMatrix& X, unsigned int k);
void copyColCol(unsigned int j, const CMatrix& X, unsigned int k);
// Scale the matrix by a constant alpha.
void scale(double alpha)
{
dscal_(nrows*ncols, alpha, vals, 1);
}
// Scale the jth column of the matrix.
void scaleCol(unsigned int j, double alpha)
{
BOUNDCHECK(j<ncols);
dscal_(nrows, alpha, vals+j*nrows, 1);
}
// Scale the ith row of the matrix.
void scaleRow(unsigned int i, double alpha)
{
BOUNDCHECK(i<nrows);
dscal_(ncols, alpha, vals+i, nrows);
}
// Level 1 BLAS axpy y c:= alpha x + y
void axpy(const CMatrix& x, double alpha)
{
DIMENSIONMATCH(x.ncols==ncols);
DIMENSIONMATCH(x.nrows==nrows);
daxpy_(ncols*nrows, alpha, x.vals, 1, vals, 1);
}
// Level 1 BLAS axpy y(i, :) := alpha*x(k, :) + y(i, :);
void axpyRowRow(unsigned int i, const CMatrix& x, unsigned int k, double alpha)
{
BOUNDCHECK(i<nrows);
BOUNDCHECK(k<x.nrows);
DIMENSIONMATCH(x.ncols==ncols);
daxpy_(ncols, alpha, x.vals+k, x.nrows, vals+i, nrows);
}
// Level 1 BLAS axpy (i, :) := alpha*x(:, j)' + y(i, :);
void axpyRowCol(unsigned int i, const CMatrix& x, unsigned int j, double alpha)
{
BOUNDCHECK(i<nrows);
BOUNDCHECK(j<x.ncols);
DIMENSIONMATCH(x.nrows==ncols);
daxpy_(ncols, alpha, x.vals+j*x.nrows, 1, vals+i, nrows);
}
// Level 1 BLAS axpy (:, j) := alpha*x(:, k) + y(:, j);
void axpyColCol(unsigned int j, const CMatrix& x, unsigned int k, double alpha)
{
BOUNDCHECK(j<ncols);
BOUNDCHECK(k<x.ncols);
DIMENSIONMATCH(x.nrows==nrows);
daxpy_(nrows, alpha, x.vals+k*x.nrows, 1, vals+j*nrows, 1);
}
// Level 1 BLAS axpy (:, j) = alpha*x(i, :)' + y(:, j);
void axpyColRow(unsigned int j, const CMatrix& x, unsigned int i, double alpha)
{
BOUNDCHECK(j<ncols);
BOUNDCHECK(i<x.nrows);
DIMENSIONMATCH(x.ncols==nrows);
daxpy_(nrows, alpha, x.vals+i, x.nrows, vals+j*nrows, 1);
}
// Level 1 BLAS axpy diag(Y) = diag(Y) + alpha*x(i, :)'
void axpyDiagRow(const CMatrix& x, unsigned int i, double alpha)
{
MATRIXPROPERTIES(isSquare());
BOUNDCHECK(i<x.nrows);
DIMENSIONMATCH(x.ncols==nrows);
daxpy_(nrows, alpha, x.vals+i, x.nrows, vals, nrows+1);
}
// Level 1 BLAS axpy diag(Y) = diag(Y) + alpha*x(i, :)'
void axpyDiagCol(const CMatrix& x, unsigned int j, double alpha)
{
MATRIXPROPERTIES(isSquare());
BOUNDCHECK(j<x.ncols);
DIMENSIONMATCH(x.nrows==nrows);
daxpy_(nrows, alpha, x.vals+j*x.nrows, 1, vals, nrows+1);
}
// Level 2 BLAS Rank 1 update: ger, A = alpha*x*y' + A;
void ger(const CMatrix& x, const CMatrix& y, double alpha)
{
DIMENSIONMATCH(x.ncols==1);
DIMENSIONMATCH(y.ncols==1);
DIMENSIONMATCH(x.nrows==nrows);
DIMENSIONMATCH(y.nrows==ncols);
dger_(nrows, ncols, alpha, x.vals, 1, y.vals, 1, vals, nrows);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(k, :)'*y(i, :) + A;
void gerRowRow(const CMatrix& x, unsigned int i, const CMatrix& y, unsigned int k, double alpha)
{
BOUNDCHECK(i<x.nrows);
BOUNDCHECK(k<y.nrows);
DIMENSIONMATCH(x.ncols==nrows);
DIMENSIONMATCH(y.ncols==ncols);
dger_(nrows, ncols, alpha, x.vals+i, x.nrows, y.vals+k, y.nrows, vals, nrows);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(:, j)*y(i, :) + A;
void gerRowCol(const CMatrix& x, unsigned int i, const CMatrix& y, unsigned int j, double alpha)
{
BOUNDCHECK(i<x.nrows);
BOUNDCHECK(j<y.ncols);
DIMENSIONMATCH(x.ncols==nrows);
DIMENSIONMATCH(y.nrows==ncols);
dger_(nrows, ncols, alpha, x.vals+i, x.nrows, y.vals+j*y.nrows, 1, vals, nrows);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(:, k)*y(:, j)' + A;
void gerColCol(const CMatrix& x, unsigned int j, const CMatrix& y, unsigned int k, double alpha)
{
BOUNDCHECK(j<x.ncols);
BOUNDCHECK(k<y.ncols);
DIMENSIONMATCH(x.nrows==nrows);
DIMENSIONMATCH(y.nrows==ncols);
dger_(nrows, ncols, alpha, x.vals+j*x.nrows, 1, y.vals+k*y.nrows, 1, vals, nrows);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(i, :)'x(:, j)' + A;
void gerColRow(const CMatrix& x, unsigned int j, const CMatrix& y, unsigned int i, double alpha)
{
BOUNDCHECK(j<x.ncols);
BOUNDCHECK(i<y.nrows);
DIMENSIONMATCH(x.nrows==nrows);
DIMENSIONMATCH(y.ncols==ncols);
dger_(nrows, ncols, alpha, x.vals+j*x.nrows, 1, y.vals+i, y.nrows, vals, nrows);
}
// Level 2 BLAS Rank 1 update: syr, A = alpha*x*x' + A;
void syr(const CMatrix& x, double alpha, const char* type)
{
MATRIXPROPERTIES(isSymmetric());
DIMENSIONMATCH(x.ncols==1);
DIMENSIONMATCH(x.nrows==nrows);
dsyr_(type, nrows, alpha, x.vals, 1, vals, nrows);
copySymmetric(type);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(i, :)'*x(i, :) + A;
void syrRow(const CMatrix& x, unsigned int i, double alpha, const char* type)
{
MATRIXPROPERTIES(isSymmetric());
BOUNDCHECK(i<x.nrows);
DIMENSIONMATCH(x.ncols==nrows);
dsyr_(type, nrows, alpha, x.vals+i, x.nrows, vals, nrows);
copySymmetric(type);
}
// Level 2 BLAS Rank 1 update: A := alpha*x(:, j)x(:, j)' + A;
void syrCol(const CMatrix& x, unsigned int j, double alpha, const char* type)
{
MATRIXPROPERTIES(isSymmetric());
BOUNDCHECK(j<x.ncols);
DIMENSIONMATCH(x.ncols==nrows);
dsyr_(type, nrows, alpha, x.vals+j*x.nrows, 1, vals, nrows);
copySymmetric(type);
}
// Return the euclidean distance squared between two row vectors.
double dist2Row(unsigned int i, const CMatrix& A, unsigned int k) const
{
DIMENSIONMATCH(ncols==A.ncols);
BOUNDCHECK(k<A.nrows);
BOUNDCHECK(i<nrows);
// |X-Y|^2 == |X|^2 + |Y|^2 - 2 X dot Y
return norm2Row(i) + A.norm2Row(k) - 2.0*dotRowRow(i, A, k);
// WVB's approach
// double val = 0;
// double *v1 = vals+i;
// double *v2 = A.vals+k;
// for (int i=0; i<ncols; i++,v1+=nrows,v2+=A.nrows) {
// double d = *v1 - *v2;
// val += d*d;
//}
// return val;
}
// Return the euclidean distance squared between two column vectors.
double dist2Col(unsigned int j, const CMatrix& A, unsigned int k) const
{
DIMENSIONMATCH(nrows==A.nrows);
BOUNDCHECK(k<A.ncols);
BOUNDCHECK(j<ncols);
return norm2Col(j) + A.norm2Col(k) - 2.0*dotColCol(j, A, k);
}
// Return the norm of the ith row of the matrix.
double normRow(unsigned int i) const
{
BOUNDCHECK(i<nrows);
return dnrm2_(ncols, vals+i, nrows);
}
// Return the squared norm of the ith row of the matrix.
double norm2Row(unsigned int i) const
{
BOUNDCHECK(i<nrows);
double val=dnrm2_(ncols, vals+i, nrows);
return val*val;
// WVB's approach
// return ddot_(ncols,vals+i,nrows,vals+i,nrows);
}
// Return the norm of the jth column of the matrix.
double normCol(unsigned int j) const
{
BOUNDCHECK(j<ncols);
return dnrm2_(nrows, vals+j*nrows, 1);
}
// Return the squared norm of the jth column of the matrix.
double norm2Col(unsigned int j) const
{
BOUNDCHECK(j<ncols);
double val=dnrm2_(nrows, vals+j*nrows, 1);
return val*val;
// WVB's approach
// return ddot_(nrows,vals+j*nrows,1,vals+j*nrows,1);
}
// Return the inner product between the ith row of the matrix and the kth row of A.
double dotRowRow(unsigned int i, const CMatrix& A, unsigned int k) const
{
BOUNDCHECK(i<nrows);
BOUNDCHECK(k<A.nrows);
return ddot_(ncols, A.vals+k, A.nrows, vals+i, nrows);
}
// Return the inner product between the ith row of the matrix and the jth column of A.
double dotRowCol(unsigned int i, const CMatrix& A, unsigned int j) const
{
BOUNDCHECK(i<nrows);
BOUNDCHECK(j<A.ncols);
return ddot_(ncols, A.vals+j*A.nrows, 1, vals+i, nrows);
}
// Return the inner product between the jth column of the matrix and the kth column of A.
double dotColCol(unsigned int j, const CMatrix& A, unsigned int k) const
{
BOUNDCHECK(j<ncols);
BOUNDCHECK(k<A.ncols);
return ddot_(nrows, A.vals+k*A.nrows, 1, vals+j*nrows, 1);
}
// Return the inner product between the jth column of the matrix and the ith row of A.
double dotColRow(unsigned int j, const CMatrix& A, unsigned int i) const
{
BOUNDCHECK(j<ncols);
BOUNDCHECK(i<A.nrows);
return ddot_(nrows, A.vals+i, A.nrows, vals+j*nrows, 1);
}
// Swap the jth and the kth columns of the matrix.
void swapCols(unsigned int j, unsigned int k)
{
BOUNDCHECK(j<ncols);
BOUNDCHECK(k<ncols);
if(j!=k)
dswap_(nrows, vals+j*nrows, 1, vals+k*nrows, 1);
}
// Swap the ith and the kth rows of the matrix.
void swapRows(unsigned int i, unsigned int k)
{
BOUNDCHECK(i<nrows);
BOUNDCHECK(k<nrows);
if(i!=k)
dswap_(ncols, vals+i, nrows, vals+k, nrows);
}
// Add columns from A to the end of the matrix.
void appendCols(const CMatrix& A)
{
DIMENSIONMATCH(rowsMatch(A));
int origNcols = ncols;
memReAllocate(0, A.ncols);
setMatrix(0, origNcols, A);
}
// Add rows from A to the end of the matrix.
void appendRows(const CMatrix& A)
{
DIMENSIONMATCH(colsMatch(A));
int origNrows = nrows;
memReAllocate(A.nrows, 0);
setMatrix(origNrows, 0, A);
}
// Get the rows firstRow:lastRow and columns firstCol:lastCol and place in a matrix C.
void getMatrix(CMatrix& matrixOut, unsigned int firstRow, unsigned int lastRow, unsigned int firstCol, unsigned int lastCol) const
{
BOUNDCHECK(firstRow<=lastRow && lastRow<nrows);
BOUNDCHECK(firstCol<=lastCol && lastCol<ncols);
DIMENSIONMATCH(matrixOut.nrows==lastRow-firstRow+1 && matrixOut.ncols==lastCol-firstCol+1);
for(unsigned int j=0; j<matrixOut.ncols; j++)
for(unsigned int i=0; i<matrixOut.nrows; i++)
matrixOut.vals[i+matrixOut.nrows*j] = vals[i+firstRow + nrows*(j+firstCol)];
}
// Get the rows in rows and columns firstCol:lastCol and place in a matrix matrixOut.
void getMatrix(CMatrix& matrixOut, vector<unsigned int> rows, unsigned int firstCol, unsigned int lastCol)
{
BOUNDCHECK(firstCol<=lastCol && lastCol<ncols);
DIMENSIONMATCH(matrixOut.nrows==rows.size() && matrixOut.ncols==lastCol-firstCol+1);
for(unsigned int i=0; i<matrixOut.nrows; i++)
{
BOUNDCHECK(rows[i]<nrows);
for(unsigned int j=0; j<matrixOut.ncols; j++)
matrixOut.vals[i+matrixOut.nrows*j] = vals[rows[i] + nrows*(j+firstCol)];
}
}
// Get the rows firstRow:lastRow and columns in cols and place in matrix matrixOut.
void getMatrix(CMatrix& matrixOut, unsigned int firstRow, unsigned int lastRow, vector<unsigned int> cols)
{
BOUNDCHECK(firstRow<=lastRow && lastRow<nrows);
DIMENSIONMATCH(matrixOut.nrows==lastRow-firstRow+1 && matrixOut.ncols==cols.size());
for(unsigned int j=0; j<matrixOut.ncols; j++)
{
BOUNDCHECK(cols[j]<ncols);
for(unsigned int i=0; i<matrixOut.nrows; i++)
matrixOut.vals[i+matrixOut.nrows*j] = vals[i+firstRow + nrows*(cols[j])];
}
}
// Get the rows from rows and columns from cols and place in matrix C.
void getMatrix(CMatrix& matrixOut, vector<unsigned int> rows, vector<unsigned int> cols)
{
DIMENSIONMATCH(matrixOut.nrows==rows.size() && matrixOut.ncols==cols.size());
for(unsigned int i=0; i<matrixOut.nrows; i++)
{
BOUNDCHECK(rows[i]<matrixOut.nrows);
for(unsigned int j=0; j<matrixOut.ncols; j++)
{
BOUNDCHECK(cols[j]<ncols);
matrixOut.vals[i+matrixOut.nrows*j] = vals[rows[i] + nrows*(cols[j])];
}
}
}
// Place A's first row and column at row, col and the rest of the matrix follows.
void setMatrix(unsigned int row, unsigned int col, const CMatrix& A)
{
BOUNDCHECK(row+A.nrows <= nrows);
BOUNDCHECK(col+A.ncols <= ncols);
for(unsigned int i=0; i<A.nrows; i++)
for(unsigned int j=0; j<A.ncols; j++)
vals[i+row+nrows*(j+col)] = A.vals[i+A.nrows*j];
}
// Place the rows of A at the locations given by rows starting at column col.
void setMatrix(const vector<unsigned int> rows, unsigned int col, const CMatrix& A)
{
DIMENSIONMATCH(rows.size()==A.nrows);
BOUNDCHECK(col+A.ncols<=ncols);
for(unsigned int i = 0; i<A.nrows; i++)
for(unsigned int j = col; j<A.ncols+col; j++)
{
BOUNDCHECK(rows[i]<nrows);
vals[rows[i]+nrows*j]=A.vals[i+A.nrows*j];
}
}
// Place the columns of A at the locations given by cols starting at row row.
void setMatrix(unsigned int row, const vector<unsigned int> cols, const CMatrix& A)
{
DIMENSIONMATCH(cols.size()==A.ncols);
BOUNDCHECK(row+A.nrows<=nrows);
for(unsigned int i=row; i<A.nrows+row; i++)
for(unsigned int j=0; j<A.ncols; j++)
{
BOUNDCHECK(cols[i]<ncols);
vals[i+nrows*cols[j]]=A.vals[i+A.nrows*j];
}
}
// Place the rows and columns of A at rows and cols.
void setMatrix(const vector<unsigned int> rows, const vector<unsigned int> cols, const CMatrix& A)
{
DIMENSIONMATCH(cols.size()==A.ncols);
DIMENSIONMATCH(rows.size()==A.nrows);
for(unsigned int i=0; i<A.nrows; i++)
for(unsigned int j=0; j<A.ncols; j++)
{
BOUNDCHECK(rows[i]<nrows);
BOUNDCHECK(cols[j]<ncols);
vals[rows[i]+nrows*cols[j]]=A.vals[i+A.nrows*j];
}
}
// In place transpose of the matrix using Algorithm 380.
void dtrans(int lwork)
{
int res;
vector<int> work(lwork);
dtrans_(vals, nrows, ncols, nrows*ncols, &work[0], lwork, res);
SANITYCHECK(res==0);
}
// In place transpose of the matrix using Algorithm 513.
void dtransr(int lwork)
{
int res;
vector<int> work(lwork);
dtransr_(vals, nrows, ncols, nrows*ncols, &work[0], lwork, res);
SANITYCHECK(res==0);
}
// In place transpose of the matrix using Algorithm 467 (currently not working).
void dxpose(int lwork)
{
// this is algorithm 467 (it is supposed to be more efficient - but doesn't work!)
std::vector<int> work(lwork);
dxpose_(vals, nrows, ncols, nrows*ncols, &work[0], lwork);
}
// Perform matrix transpose.
void trans()
{
// if rows or columns are 1 dimensional then you don't need to move elements.
if (nrows!=1 && ncols!=1)
dtransr((nrows+ncols)/2); // this is algorithm 513 (467 doesn't seem to work)
// if the matrix is square then you don't need to swap rows and columns.
if (!isSquare())
{
int temp = nrows;
nrows = ncols;
ncols = temp;
}
}
// Multiply the elements of the matrix by the elements of A.
void multiply(const CMatrix& A)
{
// if A is a row or column vector it is `replicated' before the operation.
if(A.nrows==1) {
DIMENSIONMATCH(A.ncols==ncols);
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++)
vals[i+nrows*j] *= A.vals[j];
}
else if(A.ncols==1) {
DIMENSIONMATCH(A.nrows==nrows);
for(unsigned int j=0; j<ncols; j++)
for(unsigned int i=0; i<nrows; i++)
vals[i+nrows*j] *= A.vals[i];
}
else {
DIMENSIONMATCH(A.nrows==nrows && A.ncols == ncols);
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] *= A.vals[i];
}
}
// Add a scalar to the elements of the matrix.
void add(double c) {
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] += c;
}
// Add a scalar to a column of the matrix.
void addCol(unsigned int j, double c) {
for(unsigned int i=0; i<nrows; i++)
vals[i+nrows*j] += c;
}
// Add a scalar to a row of the matrix.
void addRow(unsigned int i, double c)
{
for(unsigned int j=0; j<ncols; j++)
vals[i+nrows*j] += c;
}
// Add a scalar to diagonal of the matrix.
void addDiag(double c)
{
MATRIXPROPERTIES(isSquare());
for(unsigned int j=0; j<ncols; j++)
vals[j+nrows*j] += c;
}
// Add a matrix to the matrix.
void add(const CMatrix& A)
{
// if A is a row or column vector it is `replicated' before the operation.
if(A.nrows==1)
{
DIMENSIONMATCH(A.ncols==ncols);
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++)
vals[i+nrows*j] += A.vals[j];
}
else if(A.ncols==1)
{
DIMENSIONMATCH(A.nrows==nrows);
for(unsigned int j=0; j<ncols; j++)
for(unsigned int i=0; i<nrows; i++)
vals[i+nrows*j] += A.vals[i];
}
else
{
DIMENSIONMATCH(A.nrows==nrows && A.ncols == ncols);
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] += A.vals[i];
}
}
// Subtract a scalar from the elements of the matrix.
void subtract(double c)
{
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] -= c;
}
// Subtract a matrix from the matrix.
void subtract(const CMatrix& A)
{
// if A is a row or column vector it is `replicated' before the operation.
if(A.nrows==1)
{
DIMENSIONMATCH(A.ncols==ncols);
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++)
vals[i+nrows*j] -= A.vals[j];
}
else if(A.ncols==1)
{
DIMENSIONMATCH(A.nrows==nrows);
for(unsigned int j=0; j<ncols; j++)
for(unsigned int i=0; i<nrows; i++)
vals[i+nrows*j] -= A.vals[i];
}
else
{
DIMENSIONMATCH(A.nrows==nrows && A.ncols == ncols);
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] -= A.vals[i];
}
}
void operator+=(double c)
{
add(c);
}
void operator+=(const CMatrix& A)
{
add(A);
}
void operator-=(double c)
{
subtract(c);
}
void operator-=(const CMatrix& A)
{
subtract(A);
}
void operator*=(double c)
{
multiply(c);
}
void operator*=(const CMatrix& A)
{
multiply(A);
}
void operator-()
{
negate();
}
// element by element operations
// the MATLAB .* (element by element multiply)
void dotMultiply(const CMatrix& A)
{
DIMENSIONMATCH(dimensionsMatch(A));
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] = vals[i]*A.getVal(i);
}
void dotMultiplyRowRow(unsigned int i, const CMatrix& A, unsigned int k)
{
DIMENSIONMATCH(ncols==A.ncols);
for(unsigned int j=0; j<ncols; j++)
vals[i + nrows*j] = vals[i + nrows*j]*A.getVal(k, j);
}
void dotMultiplyRowCol(unsigned int i, const CMatrix& A, unsigned int j)
{
DIMENSIONMATCH(ncols==A.nrows);
for(unsigned int k=0; k<ncols; k++)
vals[i + nrows*k] = vals[i + nrows*k]*A.getVal(k, j);
}
void dotMultiplyColRow(unsigned int j, const CMatrix& A, unsigned int i)
{
DIMENSIONMATCH(nrows==A.ncols);
for(unsigned int k=0; k<nrows; k++)
vals[k + nrows*j] = vals[k + nrows*j]*A.getVal(i, k);
}
void dotMultiplyColCol(unsigned int j, const CMatrix& A, unsigned int k)
{
DIMENSIONMATCH(nrows==A.nrows);
for(unsigned int i=0; i<nrows; i++)
vals[i + nrows*j] = vals[i + nrows*j]*A.getVal(i, k);
}
// the MATLAB ./ (element by element divide)
void dotDivide(const CMatrix& A)
{
DIMENSIONMATCH(dimensionsMatch(A));
for(unsigned int i=0; i<nrows*ncols; i++)
vals[i] = vals[i]/A.getVal(i);
}
void dotDivideRowRow(unsigned int i, const CMatrix& A, unsigned int k)
{
DIMENSIONMATCH(ncols==A.ncols);
for(unsigned int j=0; j<ncols; j++)
vals[i + nrows*j] = vals[i + nrows*j]/A.getVal(k, j);
}
void dotDivideRowCol(unsigned int i, const CMatrix& A, unsigned int j)
{
DIMENSIONMATCH(ncols==A.nrows);
for(unsigned int k=0; k<ncols; k++)
vals[i + nrows*k] = vals[i + nrows*k]/A.getVal(k, j);
}
void dotDivideColRow(unsigned int j, const CMatrix& A, unsigned int i)
{
DIMENSIONMATCH(nrows==A.ncols);
for(unsigned int k=0; k<nrows; k++)
vals[k + nrows*j] = vals[k + nrows*j]/A.getVal(i, k);
}
void dotDivideColCol(unsigned int j, const CMatrix& A, unsigned int k)
{
if(nrows!=A.nrows)
for(unsigned int i=0; i<nrows; i++)
vals[i + nrows*j] = vals[i + nrows*j]/A.getVal(i, k);
}
// invert each element of the matrix.
void invElements()
{
for(unsigned int i = 0; i<nrows*ncols; i++)