2

我正在尝试计算 Boost Ublas 矩阵的所有元素的平方根。到目前为止,我有这个,它有效。

#include <iostream>
#include "boost\numeric\ublas\matrix.hpp"
#include <Windows.h>
#include <math.h>
#include <cmath>
#include <algorithm>
typedef boost::numeric::ublas::matrix<float> matrix;
const size_t X_SIZE = 10;
const size_t Y_SIZE = 10;
void UblasExpr();


int main()
{
    UblasExpr();
    return 0;
}

void UblasExpr()
{
    matrix m1, m2, m3;
    m1.resize(X_SIZE, Y_SIZE);
    m2.resize(X_SIZE, Y_SIZE);
    m3.resize(X_SIZE, Y_SIZE);

    for (int i = 0; i < X_SIZE; i++)
    {
        for (int j = 0; j < Y_SIZE; j++)
        {
            m1(i, j) = 2;
            m2(i, j) = 10;
        }
    }

    m3 = element_prod(m1, m2);
    std::transform(m1.data().begin(), m1.data().end(), m3.data().begin(), std::sqrtf);
    for (int i = 0; i < X_SIZE; i++)
    {
        for (int j = 0; j < Y_SIZE; j++)
        {
            std::cout << m3(i, j) << "   ";
        }
        std::cout << std::endl;
    }
}

但是,我不想使用 std::transform,而是做这样的事情: m3 = sqrtf(m1);

有没有办法让它工作?我的应用程序对性能非常敏感,因此只有在不降低效率的情况下才能接受替代方案。

PS 我想为许多其他操作执行此操作,例如 log10f、cos、acos、sin、asin、pow。我的代码中需要这些。

4

1 回答 1

3

您可以使用适当的签名定义自己的 sqrt 函数:

typedef boost::numeric::ublas::matrix<float> matrix;
matrix sqrt_element(const matrix& a)
{
   matrix result(a.size1(), a.size2());
   std::transform(a.data().begin(), a.data().end(), result.data().begin(), std::sqrtf);
   return result;
}

您还可以定义一个通用的“apply_elementwise”以将可调用对象作为参数(未经测试/未编译):

typedef boost::numeric::ublas::matrix<float> matrix;

template <typename CALLABLE>
matrix apply_elementwise(const CALLABLE& f, const matrix& a)
{
   matrix result(a.size1(), a.size2());
   std::transform(a.data().begin(), a.data().end(), result.data().begin(), f);
   return result;
}

然后你可以把它称为:

matrix y(apply_elementwise(std::sqrt, x));
matrix z;
z = apply_elementwise(std::cos,  x);

在这些函数中,我们按值返回一个矩阵。理想情况下,您要确保您使用的矩阵类使用右值引用构造函数和赋值运算符来最小化数据复制。

于 2014-07-05T18:33:01.060 回答