stereo-vision
All Data Structures Namespaces Functions Modules Pages
matrix.cpp
1 /*
2 Copyright 2011. All rights reserved.
3 Institute of Measurement and Control Systems
4 Karlsruhe Institute of Technology, Germany
5 
6 This file is part of libviso2.
7 Authors: Andreas Geiger
8 
9 libviso2 is free software; you can redistribute it and/or modify it under the
10 terms of the GNU General Public License as published by the Free Software
11 Foundation; either version 2 of the License, or any later version.
12 
13 libviso2 is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
15 PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License along with
18 libviso2; if not, write to the Free Software Foundation, Inc., 51 Franklin
19 Street, Fifth Floor, Boston, MA 02110-1301, USA
20 */
21 
22 #include "matrix.h"
23 #include <math.h>
24 #include <algorithm>
25 
26 #define SWAP(a,b) {temp=a;a=b;b=temp;}
27 #define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
28 static FLOAT sqrarg;
29 #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg)
30 static FLOAT maxarg1,maxarg2;
31 #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ? (maxarg1) : (maxarg2))
32 static int32_t iminarg1,iminarg2;
33 #define IMIN(a,b) (iminarg1=(a),iminarg2=(b),(iminarg1) < (iminarg2) ? (iminarg1) : (iminarg2))
34 
35 
36 using namespace std;
37 
38 Matrix::Matrix () {
39  m = 0;
40  n = 0;
41  val = 0;
42 }
43 
44 Matrix::Matrix (const int32_t m_,const int32_t n_) {
45  allocateMemory(m_,n_);
46 }
47 
48 Matrix::Matrix (const int32_t m_,const int32_t n_,const FLOAT* val_) {
49  allocateMemory(m_,n_);
50  int32_t k=0;
51  for (int32_t i=0; i<m_; i++)
52  for (int32_t j=0; j<n_; j++)
53  val[i][j] = val_[k++];
54 }
55 
56 Matrix::Matrix (const Matrix &M) {
57  allocateMemory(M.m,M.n);
58  for (int32_t i=0; i<M.m; i++)
59  memcpy(val[i],M.val[i],M.n*sizeof(FLOAT));
60 }
61 
62 Matrix::~Matrix () {
63  releaseMemory();
64 }
65 
66 Matrix& Matrix::operator= (const Matrix &M) {
67  if (this!=&M) {
68  if (M.m!=m || M.n!=n) {
69  releaseMemory();
70  allocateMemory(M.m,M.n);
71  }
72  if (M.n>0)
73  for (int32_t i=0; i<M.m; i++)
74  memcpy(val[i],M.val[i],M.n*sizeof(FLOAT));
75  }
76  return *this;
77 }
78 
79 void Matrix::getData(FLOAT* val_,int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
80  if (i2==-1) i2 = m-1;
81  if (j2==-1) j2 = n-1;
82  int32_t k=0;
83  for (int32_t i=i1; i<=i2; i++)
84  for (int32_t j=j1; j<=j2; j++)
85  val_[k++] = val[i][j];
86 }
87 
88 Matrix Matrix::getMat(int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
89  if (i2==-1) i2 = m-1;
90  if (j2==-1) j2 = n-1;
91  if (i1<0 || i2>=m || j1<0 || j2>=n || i2<i1 || j2<j1) {
92  cerr << "ERROR: Cannot get submatrix [" << i1 << ".." << i2 <<
93  "] x [" << j1 << ".." << j2 << "]" <<
94  " of a (" << m << "x" << n << ") matrix." << endl;
95  exit(0);
96  }
97  Matrix M(i2-i1+1,j2-j1+1);
98  for (int32_t i=0; i<M.m; i++)
99  for (int32_t j=0; j<M.n; j++)
100  M.val[i][j] = val[i1+i][j1+j];
101  return M;
102 }
103 
104 void Matrix::setMat(const Matrix &M,const int32_t i1,const int32_t j1) {
105  if (i1<0 || j1<0 || i1+M.m>m || j1+M.n>n) {
106  cerr << "ERROR: Cannot set submatrix [" << i1 << ".." << i1+M.m-1 <<
107  "] x [" << j1 << ".." << j1+M.n-1 << "]" <<
108  " of a (" << m << "x" << n << ") matrix." << endl;
109  exit(0);
110  }
111  for (int32_t i=0; i<M.m; i++)
112  for (int32_t j=0; j<M.n; j++)
113  val[i1+i][j1+j] = M.val[i][j];
114 }
115 
116 void Matrix::setVal(FLOAT s,int32_t i1,int32_t j1,int32_t i2,int32_t j2) {
117  if (i2==-1) i2 = m-1;
118  if (j2==-1) j2 = n-1;
119  if (i2<i1 || j2<j1) {
120  cerr << "ERROR in setVal: Indices must be ordered (i1<=i2, j1<=j2)." << endl;
121  exit(0);
122  }
123  for (int32_t i=i1; i<=i2; i++)
124  for (int32_t j=j1; j<=j2; j++)
125  val[i][j] = s;
126 }
127 
128 void Matrix::setDiag(FLOAT s,int32_t i1,int32_t i2) {
129  if (i2==-1) i2 = min(m-1,n-1);
130  for (int32_t i=i1; i<=i2; i++)
131  val[i][i] = s;
132 }
133 
134 void Matrix::zero() {
135  setVal(0);
136 }
137 
138 Matrix Matrix::extractCols (vector<int> idx) {
139  Matrix M(m,idx.size());
140  for (int32_t j=0; j<M.n; j++)
141  if (idx[j]<n)
142  for (int32_t i=0; i<m; i++)
143  M.val[i][j] = val[i][idx[j]];
144  return M;
145 }
146 
147 Matrix Matrix::eye (const int32_t m) {
148  Matrix M(m,m);
149  for (int32_t i=0; i<m; i++)
150  M.val[i][i] = 1;
151  return M;
152 }
153 
154 void Matrix::eye () {
155  for (int32_t i=0; i<m; i++)
156  for (int32_t j=0; j<n; j++)
157  val[i][j] = 0;
158  for (int32_t i=0; i<min(m,n); i++)
159  val[i][i] = 1;
160 }
161 
162 Matrix Matrix::diag (const Matrix &M) {
163  if (M.m>1 && M.n==1) {
164  Matrix D(M.m,M.m);
165  for (int32_t i=0; i<M.m; i++)
166  D.val[i][i] = M.val[i][0];
167  return D;
168  } else if (M.m==1 && M.n>1) {
169  Matrix D(M.n,M.n);
170  for (int32_t i=0; i<M.n; i++)
171  D.val[i][i] = M.val[0][i];
172  return D;
173  }
174  cout << "ERROR: Trying to create diagonal matrix from vector of size (" << M.m << "x" << M.n << ")" << endl;
175  exit(0);
176 }
177 
178 Matrix Matrix::reshape(const Matrix &M,int32_t m_,int32_t n_) {
179  if (M.m*M.n != m_*n_) {
180  cerr << "ERROR: Trying to reshape a matrix of size (" << M.m << "x" << M.n <<
181  ") to size (" << m_ << "x" << n_ << ")" << endl;
182  exit(0);
183  }
184  Matrix M2(m_,n_);
185  for (int32_t k=0; k<m_*n_; k++) {
186  int32_t i1 = k/M.n;
187  int32_t j1 = k%M.n;
188  int32_t i2 = k/n_;
189  int32_t j2 = k%n_;
190  M2.val[i2][j2] = M.val[i1][j1];
191  }
192  return M2;
193 }
194 
195 Matrix Matrix::rotMatX (const FLOAT &angle) {
196  FLOAT s = sin(angle);
197  FLOAT c = cos(angle);
198  Matrix R(3,3);
199  R.val[0][0] = +1;
200  R.val[1][1] = +c;
201  R.val[1][2] = -s;
202  R.val[2][1] = +s;
203  R.val[2][2] = +c;
204  return R;
205 }
206 
207 Matrix Matrix::rotMatY (const FLOAT &angle) {
208  FLOAT s = sin(angle);
209  FLOAT c = cos(angle);
210  Matrix R(3,3);
211  R.val[0][0] = +c;
212  R.val[0][2] = +s;
213  R.val[1][1] = +1;
214  R.val[2][0] = -s;
215  R.val[2][2] = +c;
216  return R;
217 }
218 
219 Matrix Matrix::rotMatZ (const FLOAT &angle) {
220  FLOAT s = sin(angle);
221  FLOAT c = cos(angle);
222  Matrix R(3,3);
223  R.val[0][0] = +c;
224  R.val[0][1] = -s;
225  R.val[1][0] = +s;
226  R.val[1][1] = +c;
227  R.val[2][2] = +1;
228  return R;
229 }
230 
231 Matrix Matrix::operator+ (const Matrix &M) {
232  const Matrix &A = *this;
233  const Matrix &B = M;
234  if (A.m!=B.m || A.n!=B.n) {
235  cerr << "ERROR: Trying to add matrices of size (" << A.m << "x" << A.n <<
236  ") and (" << B.m << "x" << B.n << ")" << endl;
237  exit(0);
238  }
239  Matrix C(A.m,A.n);
240  for (int32_t i=0; i<m; i++)
241  for (int32_t j=0; j<n; j++)
242  C.val[i][j] = A.val[i][j]+B.val[i][j];
243  return C;
244 }
245 
246 Matrix Matrix::operator- (const Matrix &M) {
247  const Matrix &A = *this;
248  const Matrix &B = M;
249  if (A.m!=B.m || A.n!=B.n) {
250  cerr << "ERROR: Trying to subtract matrices of size (" << A.m << "x" << A.n <<
251  ") and (" << B.m << "x" << B.n << ")" << endl;
252  exit(0);
253  }
254  Matrix C(A.m,A.n);
255  for (int32_t i=0; i<m; i++)
256  for (int32_t j=0; j<n; j++)
257  C.val[i][j] = A.val[i][j]-B.val[i][j];
258  return C;
259 }
260 
261 Matrix Matrix::operator* (const Matrix &M) {
262  const Matrix &A = *this;
263  const Matrix &B = M;
264  if (A.n!=B.m) {
265  cerr << "ERROR: Trying to multiply matrices of size (" << A.m << "x" << A.n <<
266  ") and (" << B.m << "x" << B.n << ")" << endl;
267  exit(0);
268  }
269  Matrix C(A.m,B.n);
270  for (int32_t i=0; i<A.m; i++)
271  for (int32_t j=0; j<B.n; j++)
272  for (int32_t k=0; k<A.n; k++)
273  C.val[i][j] += A.val[i][k]*B.val[k][j];
274  return C;
275 }
276 
277 Matrix Matrix::operator* (const FLOAT &s) {
278  Matrix C(m,n);
279  for (int32_t i=0; i<m; i++)
280  for (int32_t j=0; j<n; j++)
281  C.val[i][j] = val[i][j]*s;
282  return C;
283 }
284 
285 Matrix Matrix::operator/ (const Matrix &M) {
286  const Matrix &A = *this;
287  const Matrix &B = M;
288 
289  if (A.m==B.m && A.n==B.n) {
290  Matrix C(A.m,A.n);
291  for (int32_t i=0; i<A.m; i++)
292  for (int32_t j=0; j<A.n; j++)
293  if (B.val[i][j]!=0)
294  C.val[i][j] = A.val[i][j]/B.val[i][j];
295  return C;
296 
297  } else if (A.m==B.m && B.n==1) {
298  Matrix C(A.m,A.n);
299  for (int32_t i=0; i<A.m; i++)
300  for (int32_t j=0; j<A.n; j++)
301  if (B.val[i][0]!=0)
302  C.val[i][j] = A.val[i][j]/B.val[i][0];
303  return C;
304 
305  } else if (A.n==B.n && B.m==1) {
306  Matrix C(A.m,A.n);
307  for (int32_t i=0; i<A.m; i++)
308  for (int32_t j=0; j<A.n; j++)
309  if (B.val[0][j]!=0)
310  C.val[i][j] = A.val[i][j]/B.val[0][j];
311  return C;
312 
313  } else {
314  cerr << "ERROR: Trying to divide matrices of size (" << A.m << "x" << A.n <<
315  ") and (" << B.m << "x" << B.n << ")" << endl;
316  exit(0);
317  }
318 }
319 
320 Matrix Matrix::operator/ (const FLOAT &s) {
321  if (fabs(s)<1e-20) {
322  cerr << "ERROR: Trying to divide by zero!" << endl;
323  exit(0);
324  }
325  Matrix C(m,n);
326  for (int32_t i=0; i<m; i++)
327  for (int32_t j=0; j<n; j++)
328  C.val[i][j] = val[i][j]/s;
329  return C;
330 }
331 
332 Matrix Matrix::operator- () {
333  Matrix C(m,n);
334  for (int32_t i=0; i<m; i++)
335  for (int32_t j=0; j<n; j++)
336  C.val[i][j] = -val[i][j];
337  return C;
338 }
339 
340 Matrix Matrix::operator~ () {
341  Matrix C(n,m);
342  for (int32_t i=0; i<m; i++)
343  for (int32_t j=0; j<n; j++)
344  C.val[j][i] = val[i][j];
345  return C;
346 }
347 
348 FLOAT Matrix::l2norm () {
349  FLOAT norm = 0;
350  for (int32_t i=0; i<m; i++)
351  for (int32_t j=0; j<n; j++)
352  norm += val[i][j]*val[i][j];
353  return sqrt(norm);
354 }
355 
356 FLOAT Matrix::mean () {
357  FLOAT mean = 0;
358  for (int32_t i=0; i<m; i++)
359  for (int32_t j=0; j<n; j++)
360  mean += val[i][j];
361  return mean/(FLOAT)(m*n);
362 }
363 
364 Matrix Matrix::cross (const Matrix &a, const Matrix &b) {
365  if (a.m!=3 || a.n!=1 || b.m!=3 || b.n!=1) {
366  cerr << "ERROR: Cross product vectors must be of size (3x1)" << endl;
367  exit(0);
368  }
369  Matrix c(3,1);
370  c.val[0][0] = a.val[1][0]*b.val[2][0]-a.val[2][0]*b.val[1][0];
371  c.val[1][0] = a.val[2][0]*b.val[0][0]-a.val[0][0]*b.val[2][0];
372  c.val[2][0] = a.val[0][0]*b.val[1][0]-a.val[1][0]*b.val[0][0];
373  return c;
374 }
375 
376 Matrix Matrix::inv (const Matrix &M) {
377  if (M.m!=M.n) {
378  cerr << "ERROR: Trying to invert matrix of size (" << M.m << "x" << M.n << ")" << endl;
379  exit(0);
380  }
381  Matrix A(M);
382  Matrix B = eye(M.m);
383  B.solve(A);
384  return B;
385 }
386 
387 bool Matrix::inv () {
388  if (m!=n) {
389  cerr << "ERROR: Trying to invert matrix of size (" << m << "x" << n << ")" << endl;
390  exit(0);
391  }
392  Matrix A(*this);
393  eye();
394  solve(A);
395  return true;
396 }
397 
398 FLOAT Matrix::det () {
399 
400  if (m != n) {
401  cerr << "ERROR: Trying to compute determinant of a matrix of size (" << m << "x" << n << ")" << endl;
402  exit(0);
403  }
404 
405  Matrix A(*this);
406  int32_t *idx = (int32_t*)malloc(m*sizeof(int32_t));
407  FLOAT d;
408  A.lu(idx,d);
409  for( int32_t i=0; i<m; i++)
410  d *= A.val[i][i];
411  free(idx);
412 }
413 
414 bool Matrix::solve (const Matrix &M, FLOAT eps) {
415 
416  // substitutes
417  const Matrix &A = M;
418  Matrix &B = *this;
419 
420  if (A.m != A.n || A.m != B.m || A.m<1 || B.n<1) {
421  cerr << "ERROR: Trying to eliminate matrices of size (" << A.m << "x" << A.n <<
422  ") and (" << B.m << "x" << B.n << ")" << endl;
423  exit(0);
424  }
425 
426  // index vectors for bookkeeping on the pivoting
427  int32_t* indxc = new int32_t[m];
428  int32_t* indxr = new int32_t[m];
429  int32_t* ipiv = new int32_t[m];
430 
431  // loop variables
432  int32_t i, icol, irow, j, k, l, ll;
433  FLOAT big, dum, pivinv, temp;
434 
435  // initialize pivots to zero
436  for (j=0;j<m;j++) ipiv[j]=0;
437 
438  // main loop over the columns to be reduced
439  for (i=0;i<m;i++) {
440 
441  big=0.0;
442 
443  // search for a pivot element
444  for (j=0;j<m;j++)
445  if (ipiv[j]!=1)
446  for (k=0;k<m;k++)
447  if (ipiv[k]==0)
448  if (fabs(A.val[j][k])>=big) {
449  big=fabs(A.val[j][k]);
450  irow=j;
451  icol=k;
452  }
453  ++(ipiv[icol]);
454 
455  // We now have the pivot element, so we interchange rows, if needed, to put the pivot
456  // element on the diagonal. The columns are not physically interchanged, only relabeled.
457  if (irow != icol) {
458  for (l=0;l<m;l++) SWAP(A.val[irow][l], A.val[icol][l])
459  for (l=0;l<n;l++) SWAP(B.val[irow][l], B.val[icol][l])
460  }
461 
462  indxr[i]=irow; // We are now ready to divide the pivot row by the
463  indxc[i]=icol; // pivot element, located at irow and icol.
464 
465  // check for singularity
466  if (fabs(A.val[icol][icol]) < eps) {
467  delete[] indxc;
468  delete[] indxr;
469  delete[] ipiv;
470  return false;
471  }
472 
473  pivinv=1.0/A.val[icol][icol];
474  A.val[icol][icol]=1.0;
475  for (l=0;l<m;l++) A.val[icol][l] *= pivinv;
476  for (l=0;l<n;l++) B.val[icol][l] *= pivinv;
477 
478  // Next, we reduce the rows except for the pivot one
479  for (ll=0;ll<m;ll++)
480  if (ll!=icol) {
481  dum = A.val[ll][icol];
482  A.val[ll][icol] = 0.0;
483  for (l=0;l<m;l++) A.val[ll][l] -= A.val[icol][l]*dum;
484  for (l=0;l<n;l++) B.val[ll][l] -= B.val[icol][l]*dum;
485  }
486  }
487 
488  // This is the end of the main loop over columns of the reduction. It only remains to unscramble
489  // the solution in view of the column interchanges. We do this by interchanging pairs of
490  // columns in the reverse order that the permutation was built up.
491  for (l=m-1;l>=0;l--) {
492  if (indxr[l]!=indxc[l])
493  for (k=0;k<m;k++)
494  SWAP(A.val[k][indxr[l]], A.val[k][indxc[l]])
495  }
496 
497  // success
498  delete[] indxc;
499  delete[] indxr;
500  delete[] ipiv;
501  return true;
502 }
503 
504 // Given a matrix a[1..n][1..n], this routine replaces it by the LU decomposition of a rowwise
505 // permutation of itself. a and n are input. a is output, arranged as in equation (2.3.14) above;
506 // indx[1..n] is an output vector that records the row permutation effected by the partial
507 // pivoting; d is output as ±1 depending on whether the number of row interchanges was even
508 // or odd, respectively. This routine is used in combination with lubksb to solve linear equations
509 // or invert a matrix.
510 
511 bool Matrix::lu(int32_t *idx, FLOAT &d, FLOAT eps) {
512 
513  if (m != n) {
514  cerr << "ERROR: Trying to LU decompose a matrix of size (" << m << "x" << n << ")" << endl;
515  exit(0);
516  }
517 
518  int32_t i,imax,j,k;
519  FLOAT big,dum,sum,temp;
520  FLOAT* vv = (FLOAT*)malloc(n*sizeof(FLOAT)); // vv stores the implicit scaling of each row.
521  d = 1.0;
522  for (i=0; i<n; i++) { // Loop over rows to get the implicit scaling information.
523  big = 0.0;
524  for (j=0; j<n; j++)
525  if ((temp=fabs(val[i][j]))>big)
526  big = temp;
527  if (big == 0.0) { // No nonzero largest element.
528  free(vv);
529  return false;
530  }
531  vv[i] = 1.0/big; // Save the scaling.
532  }
533  for (j=0; j<n; j++) { // This is the loop over columns of Crout’s method.
534  for (i=0; i<j; i++) { // This is equation (2.3.12) except for i = j.
535  sum = val[i][j];
536  for (k=0; k<i; k++)
537  sum -= val[i][k]*val[k][j];
538  val[i][j] = sum;
539  }
540  big = 0.0; // Initialize the search for largest pivot element.
541  for (i=j; i<n; i++) {
542  sum = val[i][j];
543  for (k=0; k<j; k++)
544  sum -= val[i][k]*val[k][j];
545  val[i][j] = sum;
546  if ( (dum=vv[i]*fabs(sum))>=big) {
547  big = dum;
548  imax = i;
549  }
550  }
551  if (j!=imax) { // Do we need to interchange rows?
552  for (k=0; k<n; k++) { // Yes, do so...
553  dum = val[imax][k];
554  val[imax][k] = val[j][k];
555  val[j][k] = dum;
556  }
557  d = -d; // ...and change the parity of d.
558  vv[imax]=vv[j]; // Also interchange the scale factor.
559  }
560  idx[j] = imax;
561  if (j!=n-1) { // Now, finally, divide by the pivot element.
562  dum = 1.0/val[j][j];
563  for (i=j+1; i<n; i++)
564  val[i][j] *= dum;
565  }
566  } // Go back for the next column in the reduction.
567 
568  // success
569  free(vv);
570  return true;
571 }
572 
573 // Given a matrix M/A[1..m][1..n], this routine computes its singular value decomposition, M/A =
574 // U·W·V T. Thematrix U replaces a on output. The diagonal matrix of singular values W is output
575 // as a vector w[1..n]. Thematrix V (not the transpose V T ) is output as v[1..n][1..n].
576 void Matrix::svd(Matrix &U2,Matrix &W,Matrix &V) {
577 
578  Matrix U = Matrix(*this);
579  U2 = Matrix(m,m);
580  V = Matrix(n,n);
581 
582  FLOAT* w = (FLOAT*)malloc(n*sizeof(FLOAT));
583  FLOAT* rv1 = (FLOAT*)malloc(n*sizeof(FLOAT));
584 
585  int32_t flag,i,its,j,jj,k,l,nm;
586  FLOAT anorm,c,f,g,h,s,scale,x,y,z;
587 
588  g = scale = anorm = 0.0; // Householder reduction to bidiagonal form.
589  for (i=0;i<n;i++) {
590  l = i+1;
591  rv1[i] = scale*g;
592  g = s = scale = 0.0;
593  if (i < m) {
594  for (k=i;k<m;k++) scale += fabs(U.val[k][i]);
595  if (scale) {
596  for (k=i;k<m;k++) {
597  U.val[k][i] /= scale;
598  s += U.val[k][i]*U.val[k][i];
599  }
600  f = U.val[i][i];
601  g = -SIGN(sqrt(s),f);
602  h = f*g-s;
603  U.val[i][i] = f-g;
604  for (j=l;j<n;j++) {
605  for (s=0.0,k=i;k<m;k++) s += U.val[k][i]*U.val[k][j];
606  f = s/h;
607  for (k=i;k<m;k++) U.val[k][j] += f*U.val[k][i];
608  }
609  for (k=i;k<m;k++) U.val[k][i] *= scale;
610  }
611  }
612  w[i] = scale*g;
613  g = s = scale = 0.0;
614  if (i<m && i!=n-1) {
615  for (k=l;k<n;k++) scale += fabs(U.val[i][k]);
616  if (scale) {
617  for (k=l;k<n;k++) {
618  U.val[i][k] /= scale;
619  s += U.val[i][k]*U.val[i][k];
620  }
621  f = U.val[i][l];
622  g = -SIGN(sqrt(s),f);
623  h = f*g-s;
624  U.val[i][l] = f-g;
625  for (k=l;k<n;k++) rv1[k] = U.val[i][k]/h;
626  for (j=l;j<m;j++) {
627  for (s=0.0,k=l;k<n;k++) s += U.val[j][k]*U.val[i][k];
628  for (k=l;k<n;k++) U.val[j][k] += s*rv1[k];
629  }
630  for (k=l;k<n;k++) U.val[i][k] *= scale;
631  }
632  }
633  anorm = FMAX(anorm,(fabs(w[i])+fabs(rv1[i])));
634  }
635  for (i=n-1;i>=0;i--) { // Accumulation of right-hand transformations.
636  if (i<n-1) {
637  if (g) {
638  for (j=l;j<n;j++) // Double division to avoid possible underflow.
639  V.val[j][i]=(U.val[i][j]/U.val[i][l])/g;
640  for (j=l;j<n;j++) {
641  for (s=0.0,k=l;k<n;k++) s += U.val[i][k]*V.val[k][j];
642  for (k=l;k<n;k++) V.val[k][j] += s*V.val[k][i];
643  }
644  }
645  for (j=l;j<n;j++) V.val[i][j] = V.val[j][i] = 0.0;
646  }
647  V.val[i][i] = 1.0;
648  g = rv1[i];
649  l = i;
650  }
651  for (i=IMIN(m,n)-1;i>=0;i--) { // Accumulation of left-hand transformations.
652  l = i+1;
653  g = w[i];
654  for (j=l;j<n;j++) U.val[i][j] = 0.0;
655  if (g) {
656  g = 1.0/g;
657  for (j=l;j<n;j++) {
658  for (s=0.0,k=l;k<m;k++) s += U.val[k][i]*U.val[k][j];
659  f = (s/U.val[i][i])*g;
660  for (k=i;k<m;k++) U.val[k][j] += f*U.val[k][i];
661  }
662  for (j=i;j<m;j++) U.val[j][i] *= g;
663  } else for (j=i;j<m;j++) U.val[j][i]=0.0;
664  ++U.val[i][i];
665  }
666  for (k=n-1;k>=0;k--) { // Diagonalization of the bidiagonal form: Loop over singular values,
667  for (its=0;its<30;its++) { // and over allowed iterations.
668  flag = 1;
669  for (l=k;l>=0;l--) { // Test for splitting.
670  nm = l-1;
671  if ((FLOAT)(fabs(rv1[l])+anorm) == anorm) { flag = 0; break; }
672  if ((FLOAT)(fabs( w[nm])+anorm) == anorm) { break; }
673  }
674  if (flag) {
675  c = 0.0; // Cancellation of rv1[l], if l > 1.
676  s = 1.0;
677  for (i=l;i<=k;i++) {
678  f = s*rv1[i];
679  rv1[i] = c*rv1[i];
680  if ((FLOAT)(fabs(f)+anorm) == anorm) break;
681  g = w[i];
682  h = pythag(f,g);
683  w[i] = h;
684  h = 1.0/h;
685  c = g*h;
686  s = -f*h;
687  for (j=0;j<m;j++) {
688  y = U.val[j][nm];
689  z = U.val[j][i];
690  U.val[j][nm] = y*c+z*s;
691  U.val[j][i] = z*c-y*s;
692  }
693  }
694  }
695  z = w[k];
696  if (l==k) { // Convergence.
697  if (z<0.0) { // Singular value is made nonnegative.
698  w[k] = -z;
699  for (j=0;j<n;j++) V.val[j][k] = -V.val[j][k];
700  }
701  break;
702  }
703  if (its == 29)
704  cerr << "ERROR in SVD: No convergence in 30 iterations" << endl;
705  x = w[l]; // Shift from bottom 2-by-2 minor.
706  nm = k-1;
707  y = w[nm];
708  g = rv1[nm];
709  h = rv1[k];
710  f = ((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y);
711  g = pythag(f,1.0);
712  f = ((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x;
713  c = s = 1.0; // Next QR transformation:
714  for (j=l;j<=nm;j++) {
715  i = j+1;
716  g = rv1[i];
717  y = w[i];
718  h = s*g;
719  g = c*g;
720  z = pythag(f,h);
721  rv1[j] = z;
722  c = f/z;
723  s = h/z;
724  f = x*c+g*s;
725  g = g*c-x*s;
726  h = y*s;
727  y *= c;
728  for (jj=0;jj<n;jj++) {
729  x = V.val[jj][j];
730  z = V.val[jj][i];
731  V.val[jj][j] = x*c+z*s;
732  V.val[jj][i] = z*c-x*s;
733  }
734  z = pythag(f,h);
735  w[j] = z; // Rotation can be arbitrary if z = 0.
736  if (z) {
737  z = 1.0/z;
738  c = f*z;
739  s = h*z;
740  }
741  f = c*g+s*y;
742  x = c*y-s*g;
743  for (jj=0;jj<m;jj++) {
744  y = U.val[jj][j];
745  z = U.val[jj][i];
746  U.val[jj][j] = y*c+z*s;
747  U.val[jj][i] = z*c-y*s;
748  }
749  }
750  rv1[l] = 0.0;
751  rv1[k] = f;
752  w[k] = x;
753  }
754  }
755 
756  // sort singular values and corresponding columns of u and v
757  // by decreasing magnitude. Also, signs of corresponding columns are
758  // flipped so as to maximize the number of positive elements.
759  int32_t s2,inc=1;
760  FLOAT sw;
761  FLOAT* su = (FLOAT*)malloc(m*sizeof(FLOAT));
762  FLOAT* sv = (FLOAT*)malloc(n*sizeof(FLOAT));
763  do { inc *= 3; inc++; } while (inc <= n);
764  do {
765  inc /= 3;
766  for (i=inc;i<n;i++) {
767  sw = w[i];
768  for (k=0;k<m;k++) su[k] = U.val[k][i];
769  for (k=0;k<n;k++) sv[k] = V.val[k][i];
770  j = i;
771  while (w[j-inc] < sw) {
772  w[j] = w[j-inc];
773  for (k=0;k<m;k++) U.val[k][j] = U.val[k][j-inc];
774  for (k=0;k<n;k++) V.val[k][j] = V.val[k][j-inc];
775  j -= inc;
776  if (j < inc) break;
777  }
778  w[j] = sw;
779  for (k=0;k<m;k++) U.val[k][j] = su[k];
780  for (k=0;k<n;k++) V.val[k][j] = sv[k];
781  }
782  } while (inc > 1);
783  for (k=0;k<n;k++) { // flip signs
784  s2=0;
785  for (i=0;i<m;i++) if (U.val[i][k] < 0.0) s2++;
786  for (j=0;j<n;j++) if (V.val[j][k] < 0.0) s2++;
787  if (s2 > (m+n)/2) {
788  for (i=0;i<m;i++) U.val[i][k] = -U.val[i][k];
789  for (j=0;j<n;j++) V.val[j][k] = -V.val[j][k];
790  }
791  }
792 
793  // create vector and copy singular values
794  W = Matrix(min(m,n),1,w);
795 
796  // extract mxm submatrix U
797  U2.setMat(U.getMat(0,0,m-1,min(m-1,n-1)),0,0);
798 
799  // release temporary memory
800  free(w);
801  free(rv1);
802  free(su);
803  free(sv);
804 }
805 
806 ostream& operator<< (ostream& out,const Matrix& M) {
807  if (M.m==0 || M.n==0) {
808  out << "[empty matrix]";
809  } else {
810  char buffer[1024];
811  for (int32_t i=0; i<M.m; i++) {
812  for (int32_t j=0; j<M.n; j++) {
813  sprintf(buffer,"%12.7f ",M.val[i][j]);
814  out << buffer;
815  }
816  if (i<M.m-1)
817  out << endl;
818  }
819  }
820  return out;
821 }
822 
823 void Matrix::allocateMemory (const int32_t m_,const int32_t n_) {
824  m = abs(m_); n = abs(n_);
825  if (m==0 || n==0) {
826  val = 0;
827  return;
828  }
829  val = (FLOAT**)malloc(m*sizeof(FLOAT*));
830  val[0] = (FLOAT*)calloc(m*n,sizeof(FLOAT));
831  for(int32_t i=1; i<m; i++)
832  val[i] = val[i-1]+n;
833 }
834 
835 void Matrix::releaseMemory () {
836  if (val!=0) {
837  free(val[0]);
838  free(val);
839  }
840 }
841 
842 FLOAT Matrix::pythag(FLOAT a,FLOAT b) {
843  FLOAT absa,absb;
844  absa = fabs(a);
845  absb = fabs(b);
846  if (absa > absb)
847  return absa*sqrt(1.0+SQR(absb/absa));
848  else
849  return (absb == 0.0 ? 0.0 : absb*sqrt(1.0+SQR(absa/absb)));
850 }
851