0
votes

Hi I'm new to C++ and am trying to do something that is very easy to do with Matlab. I have a for loop which computes a vector. I would like to then store this vector so that I can access it outside of the loop.

for(ii=0; ii < numObs; ii++} {
    someVector = ...
    someMatrix[ii][:] = someVector
}

The someMatrix[ii][:] doesn't work of course, but that's what I would like to do. Any help's appreciated, thanks!

Clarification: someVector is an 1xn element vector which is computed each time in the loop. I simply want to store it in either a matrix or array (not sure what) so that I can call someMatrix[ii] and get the vector back.

1
A vector is not the same thing as a matrix. Please clarify whether you're looking to use some implementation of a matrix or vector. - George
FYI, may I suggest to look into Eigen. Excellent linear algebra library that should result friendly to Matlab users. - Emerald Weapon
Also have a look at the Armadillo c++ library, which has a syntax deliberately similar to Matlab. - mtall

1 Answers

1
votes

You're probably looking for something like:

std::vector<std::vector<double>> matrix; // matrix - vector of vectors
for(int i = 0; i < numObs; ++i) {
    std::vector<double> vec = ... // your calculations go here
    // if no C++11 - don't use std::move
    matrix.push_back(std::move(vec)); 
}

One of the drawbacks here is that you have to assure in calculation code that each vector will have same number of elements (the code above doesn't verify it).

Note, that this is definitely not the optimal way for handling matrices and I'd recommend you to take a look at some dedicated libraries (boost::numeric, OpenCV for image processing, Armadillo or one of a dozen others) if you want to perform serious computations on it.