op_cov_meat.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
  2. // Copyright 2008-2016 National ICT Australia (NICTA)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ------------------------------------------------------------------------
  15. //! \addtogroup op_cov
  16. //! @{
  17. template<typename T1>
  18. inline
  19. void
  20. op_cov::apply(Mat<typename T1::elem_type>& out, const Op<T1,op_cov>& in)
  21. {
  22. arma_extra_debug_sigprint();
  23. typedef typename T1::elem_type eT;
  24. const uword norm_type = in.aux_uword_a;
  25. const unwrap<T1> U(in.m);
  26. const Mat<eT>& A = U.M;
  27. if(A.n_elem == 0)
  28. {
  29. out.reset();
  30. return;
  31. }
  32. const Mat<eT>& AA = (A.n_rows == 1)
  33. ? Mat<eT>(const_cast<eT*>(A.memptr()), A.n_cols, A.n_rows, false, false)
  34. : Mat<eT>(const_cast<eT*>(A.memptr()), A.n_rows, A.n_cols, false, false);
  35. const uword N = AA.n_rows;
  36. const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N);
  37. const Mat<eT> tmp = AA.each_row() - mean(AA,0);
  38. out = tmp.t() * tmp;
  39. out /= norm_val;
  40. }
  41. template<typename T1>
  42. inline
  43. void
  44. op_cov::apply(Mat<typename T1::elem_type>& out, const Op< Op<T1,op_htrans>, op_cov>& in)
  45. {
  46. arma_extra_debug_sigprint();
  47. typedef typename T1::elem_type eT;
  48. const uword norm_type = in.aux_uword_a;
  49. if(is_cx<eT>::yes)
  50. {
  51. const Mat<eT> tmp = in.m; // force the evaluation of Op<T1,op_htrans>
  52. out = cov(tmp, norm_type);
  53. }
  54. else
  55. {
  56. const unwrap<T1> U(in.m.m);
  57. const Mat<eT>& A = U.M;
  58. if(A.n_elem == 0)
  59. {
  60. out.reset();
  61. return;
  62. }
  63. const Mat<eT>& AA = (A.n_cols == 1)
  64. ? Mat<eT>(const_cast<eT*>(A.memptr()), A.n_cols, A.n_rows, false, false)
  65. : Mat<eT>(const_cast<eT*>(A.memptr()), A.n_rows, A.n_cols, false, false);
  66. const uword N = AA.n_cols;
  67. const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N);
  68. const Mat<eT> tmp = AA.each_col() - mean(AA,1);
  69. out = tmp * tmp.t();
  70. out /= norm_val;
  71. }
  72. }
  73. //! @}