【问题标题】:regarding element-by-element operations in boost::ublas关于 boost::ublas 中的逐元素操作
【发布时间】:2012-05-20 20:15:56
【问题描述】:

我发现 boost::ublas 不太支持逐元素操作和顺序操作(但是效率相当高:)) 我正在尝试

D = A^2 .* B^3 .* C

其中A、B、C都是大小相同的方阵,运算符“.*”表示逐元素运算,^是矩阵的幂。用 boost:ublas,我写了

for (int n=0; n<300; n++)
{
  for (int k=0; k<300; k++)
  {
    D(n, k) = pow(abs(A(n, k)), 2)*pow(abs(B(n, k)), 3)*C(n, k);
  }
}

在我的程序中,我有许多类似上面所示的后续操作,无论如何我可以得到相同的结果,但使用一行代码而不是循环?

另外,我观察到为矩阵或向量的所有元素分配一个常数似乎是无效的

boost::numeric::ublas::vector v(100); v = 0.2;

相反,我必须使用循环再次执行分配,有更好的方法来保存一些代码吗?我的算法真的很长,并且有很多像上面提到的那样繁琐的操作。我尝试了另一个数值库 Armadillo,它提供了一种简化操作的好方法,但它目前不假设稀疏矩阵(运行我的代码将花费大约 10 次)。

【问题讨论】:

    标签: c++ matrix ublas


    【解决方案1】:

    您可以很容易地将常量分配给向量或矩阵:

    vector<double> v = scalar_vector<double>(100, 0.2);
    

    正则向量(但不是 c_vector 或 bounded_vector)甚至有一个构造函数:

    vector<double> v(100, 0.2);
    

    至于元素操作,您也可以轻松定义自己的,它只是样板代码,例如绝对权力:) :

    namespace boost { namespace numeric { namespace ublas {
    template<class M, class P>
    struct scalar_power:
        public scalar_binary_functor<M, P> {
        typedef typename scalar_binary_functor<M, P>::argument1_type argument1_type;
        typedef typename scalar_binary_functor<M, P>::argument2_type argument2_type;
        typedef typename scalar_binary_functor<M, P>::result_type result_type;
    
        static BOOST_UBLAS_INLINE
        result_type apply (argument1_type t1, argument2_type t2) {
            return pow(abs(t1), t2);
        }
    };
    
    template<class M, class P>
    BOOST_UBLAS_INLINE
    typename enable_if< is_convertible<P, typename M::value_type>,
    typename matrix_binary_scalar2_traits<M, const P, scalar_power<typename M::value_type, P> >::result_type
    >::type
    operator ^ (const matrix_expression<M> &m,
                const P &p) {
        typedef typename matrix_binary_scalar2_traits<M, const P, scalar_power<typename M::value_type, P> >::expression_type expression_type;
        return expression_type (m(), p);
    }
    }}}
    

    在此之后,您的表达式变为:

    D = element_prod(A^2, element_prod(B^3, C));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多