0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

std::vectorとEigenで簡便なテンソル計算をしたい

Last updated at Posted at 2018-12-18

データをテンソルとして保持する必要があるが、EigenのTensorはUnsupportedとか書かれていて使うのが怖い。

テンソル自体は、中間変数として出てくるだけで、そこまで複雑な計算をするつもりはなく、vectorで格納した軸に対して、和が取れれば十分。

そんな時に使う小技です。

方針

  1. std::vectorEigen::MatrixXdを使って、行列を格納
  2. accumulate関数を使い、vector方向に和を取る

accumulateの初期値として、Eigen::MatrixXd::Zero(n,m).eval()とすることで、accumulate関数を実行することができるようになるようです。
(eval()を使う理由はいまいちわかっていません)

  • コード例
# include "Eigen/Core"
# include <iostream>
# include <vector>
# include <numeric> // accumulate関数に必要
# include <typeinfo>

int main(){
  // 初期化
  std::vector<Eigen::MatrixXd> tensor;
  for (int i = 0; i < 5; ++i) {
    Eigen::MatrixXd tmp = Eigen::MatrixXd::Constant(3, 4, static_cast<double>(i) + 0.5);
    tensor.push_back(tmp);
  }
  // 和の計算
  std::cout << "sum1 = " << std::accumulate(tensor.begin(), tensor.end(), Eigen::MatrixXd::Zero(3,4).eval()) << std::endl;

参考

http://kowaimononantenai.blogspot.com/2013/11/stdaccumulatevectorstdaccumulate3.html
https://forum.kde.org/viewtopic.php?f=74&t=118075
https://eigen.tuxfamily.org/dox/TopicPitfalls.html
https://qiita.com/sakisakira/items/7c6952e59e958cefe7fa

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?