GenericMatrix.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @file GenericMatrix.cpp
  3. * @brief matrix interface for indirect matrix multiplications
  4. * @author Erik Rodner
  5. * @date 05/14/2009
  6. */
  7. #include "GenericMatrix.h"
  8. #include <assert.h>
  9. using namespace OBJREC;
  10. using namespace NICE;
  11. using namespace std;
  12. GMSparse::GMSparse ( const NICE::Matrix & A, double epsilon )
  13. {
  14. m_rows = A.rows();
  15. m_cols = A.cols();
  16. for ( u_int i = 0 ; i < m_rows ; i++ )
  17. for ( u_int j = 0 ; j < m_cols ; j++ )
  18. if (fabs(A(i, j)) > epsilon )
  19. this->A.insert ( this->A.begin(), NICE::triplet<int, int, double> ( i, j,A(i, j) ) );
  20. }
  21. void GMSparse::multiply ( NICE::Vector & y, const NICE::Vector & x ) const
  22. {
  23. assert ( x.size() == m_cols );
  24. y.resize( m_rows );
  25. y.set(0.0);
  26. for ( vector< NICE::triplet<int, int, double> >::const_iterator k = this->A.begin();
  27. k != this->A.end(); k++ )
  28. {
  29. int i = k->first;
  30. int j = k->second;
  31. double value = k->third; // = a_ij
  32. y[i] += value * x[j];
  33. }
  34. }
  35. GMCovariance::GMCovariance ( const NICE::Matrix *data )
  36. {
  37. this->data = data;
  38. m_rows = data->rows();
  39. m_cols = m_rows;
  40. }
  41. void GMCovariance::multiply ( NICE::Vector & y, const NICE::Vector & x ) const
  42. {
  43. assert ( x.size() == data->rows() );
  44. /*******************************************************************
  45. * d_k = data(:,k) vector k in the data set
  46. * f_k = d_k^T x
  47. * fSum = \sum_k f_k
  48. * In the following we use the following relationship
  49. * S = \sum_i d_i ( d_i - \mu )^T = \sum_i (d_i - \mu) (d_i - \mu)^T
  50. * Sx = \sum_i d_i ( f_i - fSum/N )
  51. * which seems to be very efficient
  52. * *****************************************************************/
  53. NICE::Vector f ( data->cols() );
  54. f.set(0.0);
  55. double fSum = 0.0;
  56. for ( uint k = 0 ; k < data->cols() ; k++ )
  57. {
  58. for ( uint d = 0 ; d < data->rows() ; d++ )
  59. f[k] += (*data)(d, k) * x[d];
  60. fSum += f[k];
  61. }
  62. y.resize(x.size());
  63. y.set(0.0);
  64. int N = data->cols();
  65. for ( uint k = 0 ; k < data->cols() ; k++ )
  66. for ( int l = 0 ; l < (int)y.size(); l++ )
  67. y[l] += ( f[k] - fSum/N ) * ( (*data)(l, k) );
  68. for ( int i = 0 ; i < (int)y.size() ; i++ )
  69. y[i] /= N;
  70. }