c++ - Boost Ublas 矩阵所有元素的平方根

标签 c++ templates c++11 boost ublas

我正在尝试计算 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);

有办法让它发挥作用吗?我的应用程序对性能非常敏感,因此只有在不损失效率的情况下才可以接受替代方案。

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

最佳答案

您可以使用适当的签名定义自己的 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);

在这些函数中,我们按值返回一个矩阵。理想情况下,您希望确保您使用的矩阵类采用右值引用构造函数和赋值运算符来最大程度地减少数据复制。

关于c++ - Boost Ublas 矩阵所有元素的平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588612/

相关文章:

c++ - 在不知道声明签名的情况下将任意函数对象存储到类成员容器中

c++ - 将类型名传递给 lambda 最简洁的方法是什么?

c++ - #include<boost> 没有这样的文件或目录

c++ - C++ 11 Cereal 序列化-版本控制

c++ - 将 QObject 接口(interface)信号连接到 lambda 插槽

c# - 有没有一种简单有效的方法可以在 C# 或 C/C++ 中列出所有 USB 设备?

c++ - c_str() 是在堆中分配内存吗?

c++ - 带 OpenCV 的灰度 C++(出现一些噪音)

c++ - 包含依赖于类成员的模板的类

java - Apache 速度 : Escape character not working