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 に答える