c++ - 在 C++ 中返回多个矩阵( Armadillo 库)

标签 c++ matrix linear-algebra armadillo

我正在使用 C++ 中的 Armadillo 库。首先我计算一个特殊矩阵(在我的代码中:P),然后我计算 QR 分解(在我的代码中:Q)。最后,我需要将 P 和 Q 以及另一个矩阵 T 返回到我的主函数。

#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
double phi(int n, int q){
...
  mat P(n,n);
  P=...
   mat Q,R;
   qr(Q,R,P);
return P:
return Q;
return Q;
...
 }

int main() {
    ...
    int n,q;
    cout<<"Enter the value of parameters n and q respectively:"<<endl;
    cin>> n>>q;
    phi(n,q);
...
}

我正在寻找一种无需使用指针和引用即可在 Armadillo 中返回这些矩阵的方法。我的矩阵很大,通常为 500*500 或 1000*1000。有人有解决办法吗?提前致谢

最佳答案

这是一个使用 std::tuple 的例子连同 std::tie

#include <iostream>
#include <armadillo>

using namespace arma;

std::tuple<mat, mat> phi(int const n, int const q)
{
    ...
    mat P(n, n);
    P = ...
    mat Q, R;
    qr(Q, R, P);
    return std::make_tuple(P, Q);
}

int main()
{
    ...
    int n, q;
    std::cout << "Enter the value of parameters n and q respectively:" << std::endl;
    std::cin >> n >> q;
    mat P, Q;
    std::tie(P, Q) = phi(n,q);
    ...
}

使用 C++17(和 structured binding 声明)你可以这样做:

#include <iostream>
#include <armadillo>

using namespace arma;

std::tuple<mat, mat> phi(int const n, int const q)
{
    ...
    mat P(n, n);
    P = ...
    mat Q, R;
    qr(Q, R, P);
    return {P, Q};
}

int main()
{
    ...
    int n,q;
    std::cout << "Enter the value of parameters n and q respectively:" << std::endl;
    std::cin >> n >> q;
    auto [P, Q] = phi(n,q);
    ...
}

关于c++ - 在 C++ 中返回多个矩阵( Armadillo 库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707298/

相关文章:

c++ - C++ 中的循环融合(如何帮助编译器?)

c - 使用 C 程序从 txt 文件中读取坐标

C 将矩阵读入动态数组

python-3.x - LU 分解速度与传统 Ax=b 的比较

julia - 如何在 Julia 中执行向量的逐元素平方根?

c++ - 使用 gcc 编译 .cpp

c++ - 使用 map 将字符串与枚举连接起来

c++ - GNU Fortran 和 C 互操作性

C++ Matrix-Chain-Order/无法获得所需的输出

c++ - 使用 GCC 编译 PARDISO 线性求解器测试用例