Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return multiple matrices in c++ (Armadillo library)

I am working with Armadillo library in C++. At first I calculate an especial matrix (in my code: P),then I calculate the QR-decomposition(in my code: Q). At the end I need to return both P and Q and also another matrix T to my main function.

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

I am looking for a method to return these matrices in armadillo with out using pointers and references.Here my matrices are huge and usually are 500*500 or 1000*1000. Does anyone have the solution? Thanks beforehand

like image 804
Ham82 Avatar asked Jan 17 '17 21:01

Ham82


1 Answers

Here is an example using std::tuple along with 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);
    ...
}

With C++17 (and a structured binding declaration) you could do it like this:

#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);
    ...
}
like image 108
Jonas Avatar answered Oct 16 '22 11:10

Jonas