1

i've recently seen this code which i believe to be the equivelant to vec2mat from matlab to C++ :

int mat vec2mat(vec V, size_t cols) {
size_t rows = std::ceil(V.n_elems / double(cols));
return V.reshape(cols, rows);// return the original vector as matrix

And i've tried to apply that to my code, but without success. I hope someone can help me find the right way to do so. Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() 
{
    int cargas[20];
    srand(time(NULL));
    int i;

    for (i = 0; i < 20; i++) 
    {
        cargas[i] = (rand() % 5) + 1;
    }

    for (i = 0; i < 20; i++)
        printf("%d ", cargas[i]);
}

(i would like to turn the vector into a 4x5 matrix)

CinCout
  • 9,486
  • 12
  • 49
  • 67

1 Answers1

1

The routine you have posted appears to be using the armadillo library. A corrected version could be:

#include <armadillo>

arma::mat vec2mat(const arma::vec& V, size_t cols)
{
  size_t rows = std::ceil(V.n_elem / double(cols));
  return arma::reshape(V, rows, cols);
}

Notice that the routine requires a armadillo type arma::vec as an input; it does not work with a C-style array, but you could, say, convert it into a arma::vec.

Please see the armadillo documentation for more information on the library.

francesco
  • 7,189
  • 7
  • 22
  • 49