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

如何用Eigen或Armadillo库在C++中实现交换矩阵?求MATLAB代码转译

使用Eigen或Armadillo在C++中实现交换矩阵

逻辑说明

交换矩阵的核心是先构造一个排列索引序列,再通过该序列重排单位矩阵的行得到目标矩阵。以下实现完全对应你提供的MATLAB代码逻辑,仅适配C++和对应库的语法特性。


Eigen实现

Eigen需要手动构造排列向量,再完成行重排:

#include <Eigen/Dense>

Eigen::MatrixXd com_mat_eigen(int m, int n) {
    const int total_size = m * n;
    Eigen::VectorXi permutation(total_size);
    
    // 构造0-based排列向量,对应MATLAB中reshape(A', 1, [])的结果(转换为0索引)
    for (int col = 0; col < n; ++col) {
        for (int row = 0; row < m; ++row) {
            permutation(col * m + row) = row * n + col;
        }
    }
    
    // 生成单位矩阵并按排列向量重排行
    Eigen::MatrixXd comm_matrix = Eigen::MatrixXd::Identity(total_size, total_size);
    Eigen::MatrixXd result(total_size, total_size);
    for (int i = 0; i < total_size; ++i) {
        result.row(i) = comm_matrix.row(permutation(i));
    }
    
    return result;
}

Armadillo实现

Armadillo语法更贴近MATLAB,实现更简洁:

#include <armadillo>

arma::mat com_mat_armadillo(int m, int n) {
    const int total_size = m * n;
    
    // 生成对应MATLAB中v的排列向量(0-based)
    arma::vec permutation = arma::reshape(
        arma::reshape(arma::linspace<arma::vec>(0, total_size - 1, total_size), m, n).t(),
        total_size,
        1
    );
    
    // 生成单位矩阵并按排列向量重排行
    arma::mat comm_matrix = arma::eye(total_size, total_size);
    comm_matrix = comm_matrix.rows(permutation);
    
    return comm_matrix;
}

与MATLAB代码的对应关系

  • MATLAB中的A = reshape(1:m*n, m, n):对应Eigen的手动索引计算,或Armadillo的arma::reshape(arma::linspace(...), m, n)
  • MATLAB中的v = reshape(A', 1, []):对应Eigen的双重循环构造排列向量,或Armadillo的转置后再reshape
  • MATLAB中的P = P(v,:):对应Eigen的逐行复制,或Armadillo的rows(permutation)方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:22:06