我将从 Python 和 Numpy 转向 C++ 和 Eigen。
在 Python 中,我可以使用属性获取 Numpy 数组/矩阵的形状(维度).shape,如下所示:
import numpy as np
m = np.array([ [ 1, 2, 3], [10, 20, 30] ])
print(m)
# [[ 1 2 3]
# [10 20 30]]
print(m.shape)
# (2, 3)
Run Code Online (Sandbox Code Playgroud)
现在,当我使用 Eigen 时,似乎没有任何属性或方法来检索形状。最简单的方法是什么?
#include <iostream>
#include "Eigen/Dense"
using std::cout;
using std::endl;
using std::string;
using Eigen::MatrixXd;
int main(int argc, char**argv)
{
MatrixXd m(2, 3);
m << 1, 2, 3, 10, 20, 30;
cout << m << endl;
// 1 2 3
// 10 20 30
cout << "shape: " << WHAT DO I PUT HERE? << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
.rows()您可以分别使用和方法从特征矩阵中检索行数和列数.cols()。
get_shape()下面是一个返回string矩阵形状表示的函数;它包含类似于 Numpy.shape属性的信息。
该EigenBase类型允许函数接受 aMatrixXd或 a VectorXd。
#include <iostream>
#include <sstream> // <-- Added
#include "Eigen/Dense"
using std::cout;
using std::endl;
using std::string;
using std::ostringstream; // <-- Added
using Eigen::MatrixXd;
using Eigen::EigenBase; // <-- Added
template <typename Derived>
std::string get_shape(const EigenBase<Derived>& x)
{
std::ostringstream oss;
oss << "(" << x.rows() << ", " << x.cols() << ")";
return oss.str();
}
int main(int argc, char**argv)
{
MatrixXd m(2, 3);
m << 1, 2, 3, 10, 20, 30;
cout << "shape: " << get_shape(m) << endl;
// shape: (2, 3)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12912 次 |
| 最近记录: |