gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:43:46 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com