glue_cov_meat.hpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 glue_cov
  16. //! @{
  17. template<typename T1, typename T2>
  18. inline
  19. void
  20. glue_cov::apply(Mat<typename T1::elem_type>& out, const Glue<T1,T2,glue_cov>& X)
  21. {
  22. arma_extra_debug_sigprint();
  23. typedef typename T1::elem_type eT;
  24. const uword norm_type = X.aux_uword;
  25. const unwrap<T1> UA(X.A);
  26. const unwrap<T2> UB(X.B);
  27. const Mat<eT>& A = UA.M;
  28. const Mat<eT>& B = UB.M;
  29. const Mat<eT>& AA = (A.n_rows == 1)
  30. ? Mat<eT>(const_cast<eT*>(A.memptr()), A.n_cols, A.n_rows, false, false)
  31. : Mat<eT>(const_cast<eT*>(A.memptr()), A.n_rows, A.n_cols, false, false);
  32. const Mat<eT>& BB = (B.n_rows == 1)
  33. ? Mat<eT>(const_cast<eT*>(B.memptr()), B.n_cols, B.n_rows, false, false)
  34. : Mat<eT>(const_cast<eT*>(B.memptr()), B.n_rows, B.n_cols, false, false);
  35. arma_debug_assert_mul_size(AA, BB, true, false, "cov()");
  36. if( (A.n_elem == 0) || (B.n_elem == 0) )
  37. {
  38. out.reset();
  39. return;
  40. }
  41. const uword N = AA.n_rows;
  42. const eT norm_val = (norm_type == 0) ? ( (N > 1) ? eT(N-1) : eT(1) ) : eT(N);
  43. const Mat<eT> tmp1 = AA.each_row() - mean(AA,0);
  44. const Mat<eT> tmp2 = BB.each_row() - mean(BB,0);
  45. out = tmp1.t() * tmp2;
  46. out /= norm_val;
  47. }
  48. //! @}