You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取C++ Eigen库中矩阵的形状(维度)?

Eigen中没有直接对应NumPy .shape的统一属性,你可以分别调用*.rows()获取矩阵行数,.cols()获取矩阵列数*,二者返回的结果对应NumPy shape元组的第一个和第二个元素。

你提供的测试代码补全后如下:

#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: (" << m.rows() << ", " << m.cols() << ")" << endl;
    // 输出结果为 shape: (2, 3)

    return 0;
}

补充说明:

  • 不管是动态尺寸矩阵(比如你用的MatrixXd)还是固定尺寸矩阵(比如Matrix3d、Matrix2f),rows()和cols()方法都适用,固定尺寸矩阵的这两个方法会在编译期完成计算,没有运行时开销。
  • 如果你习惯了NumPy的调用方式,可以自己封装一个简单的工具函数,示例如下:
#include <utility>
template <typename Derived>
std::pair<int, int> shape(const Eigen::DenseBase<Derived>& mat) {
    return {mat.rows(), mat.cols()};
}

封装完成后你就可以直接用shape(m)拿到包含行、列数的pair,和NumPy的使用习惯更贴近。

内容的提问来源于stack exchange,提问作者stackoverflowuser2010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:39:01