Question

Looking for something in C++ for easy storage and access of matrices of different sizes. I typically use R, and in R I can use a loop and store a matrix in a list as follows (toy example)

myList <- list(1)
for(i in 1:10){
myList[[i]] <- matrix(rnorm(i^2),i,i)
}

This gives me a list where myList[[i]] will then give me the i-th matrix. Is there anything like this in C++? I have seen Boost functions that can do arrays of varying sizes, but fail to apply them to matrices. Trying to use either Eigen or Armadillo if that helps narrow responses.

No correct solution

OTHER TIPS

There is 2 parts to the answer you're looking for, i.e.

  1. The matrices.
  2. The container holding all these matrices.

So, for the matrices: If you are planning on doing linear algebra operations I'd recommend using some special libraries, such as Armadillo which comes with a lot of pre-defined matrix functions (e.g. eigenvalue, matrix multiplication, etc.). If it's just basic 2D data storage with no special operation, then I'd recommend using a STL vector of vector to represent your matrices. These containers are dynamic in size (can be changed at will during execution) and all elements are accessible by index. As Patrick said, more info can be found here: cppreference.com.

An example of a 3x3 matrix of integer filled with 1s would be

std::vector< std::vector<int,int> > matrix(3,std::vector<int>(3,1));

Then, you have to store these matrices somewhere. For this, it is really going to depend on your needs. The simplest solution would be a vector of matrices (so a vector of vector of vector, really). Your code would behave exactly as in R, and you would be able to access matrix by index. The equivalent C++ code is

#include<vector>
using namespace std;
typedef  vector< vector<int,int> > int_matrix_t;
...
vector<int_matrix_t> my_vector_of_matrices(10);
for (int i = 0; i<10; ++i) {
   my_vector_of_matrices[i] = some_function_that_outputs_a_matrix(i);
}

But there is a lot of other container available. You should survey this chart and choose for yourself!

I believe you can use std::vector.

http://en.cppreference.com/w/cpp/container/vector

std::vector<Matrix> matrices;
matrices[i] = Matrix(data);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top