gpt4 book ai didi

c++ - 如何获得特征矩阵的形状(尺寸)?

转载 作者:行者123 更新时间:2023-12-04 07:14:22 27 4
gpt4 key购买 nike

我正从 Python 和 Numpy 转向 C++ 和 Eigen。

在 Python 中,我可以使用 .shape 属性获取 Numpy 数组/矩阵的形状(维度),如下所示:

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)

现在,当我使用 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;
}

最佳答案

您可以分别使用 .rows().cols() 方法从特征矩阵中检索行数和列数。

下面是一个函数 get_shape(),它返回矩阵形状的 string 表示;它包含类似于 Numpy 的 .shape 属性的信息。

EigenBase type 允许函数接受 MatrixXdVectorXd

#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;
}

关于c++ - 如何获得特征矩阵的形状(尺寸)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68877737/

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