【问题标题】:return multiple matrices in c++ (Armadillo library)在 C++ 中返回多个矩阵(犰狳库)
【发布时间】:2017-01-17 21:26:20
【问题描述】:

我正在使用 C++ 中的犰狳库。首先我计算一个特殊的矩阵(在我的代码中: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);
...
}

我正在寻找一种在犰狳中返回这些矩阵而不使用指针和引用的方法。这里我的矩阵很大,通常是 500*500 或 1000*1000。有没有人有解决方案?先谢谢了

【问题讨论】:

  • 为什么不更改 phi 的签名以包含两个指向 P 和 Q 的指针并从 main 传递它们?
  • 我想在 RCPP 中使用 phi 函数。我不确定它在那里正常工作。如果找不到其他解决方案,我必须使用指针。
  • 您可以使用std::tuplestd::tie,参见en.cppreference.com/w/cpp/utility/tuple

标签: c++ matrix linear-algebra armadillo


【解决方案1】:

这是一个使用std::tuplestd::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);
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多