Search code examples
c++arraysmatlabmatrixmatrix-indexing

How to access multiple elements of an array efficienty in C++?


This if my first post, I hope I'll meet the standards...

I'm translating into c++ (at which I'm quite new) a program originally written in MATLAB for reasons of efficiency. The piece of code I am actually working on resumes accesses to various indexes of a vector (matrix) in one step. For example, if M1 is a matrix of size, let's say, 10x15, the program would define a new one as follows:

idxs1 = [1 2 3];
idxs2 = [1 2 3 4 5];
M2 = M1 (idxs1 , idxs2);

resulting M2 as a matrix of size 3x5. Now, I guess what MATLAB actually does is access one by one the various places of M1 given by the indexes and then construct M2 by rearranging the many contents acquired, all very efficiently.

My question is, how can I reproduce such mechanism in c++? As far as I know there is no direct way to access in a row various indexes of an array, and the for loop I'm using seems rather cumbersome. Maybe there's some intelligent way to do it without demanding 'too much' processor time? Also, for the sake of educational purposes, I would be grateful if someone could explain what MATLAB actually does when such operation is performed.

Thanks in advance and sorry for the eventual inconveniences!

P.S: Just in case it adds anything to the question, I'm working with MEX files to link both languages. P.S2: By the way, I found some related questions but regarding other languages:


Solution

  • "Armadillo is a high quality C++ linear algebra library, aiming towards a good balance between speed and ease of use

    Useful for algorithm development directly in C++, or quick conversion of research code into production environments; the syntax (API) is deliberately similar to Matlab"

    Link: http://arma.sourceforge.net/