Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

データをテンソルとして保持する必要があるが、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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした