0

I have a file containing three columns I want to reshape it to matrix.

This question was answered in this link using R: Reshape three column data frame to matrix ("long" to "wide" format)

Since the input file is too big I want to use C++ for this purpose.

How can I create a matrix in C++ that have a fast access to its element?

After that I can read the big file with three columns line by line and put the value in the right place using hash key or indexing.

I think map form std lib can do it for one dimensional array.

Community
  • 1
  • 1
user1436187
  • 3,252
  • 3
  • 26
  • 59
  • "How can I create a matrix in C++ that have a fast access to its element?" By using one of the many existing [libraries](http://scicomp.stackexchange.com/a/353) – eerorika May 17 '14 at 12:39
  • I do not want it for matrix algebra I just want to create it! – user1436187 May 17 '14 at 12:58
  • You can always make a multidimensional container that uses the `[]` operator. This page is an excellent starting point to the available containers in C++: [Containers Library](http://en.cppreference.com/w/cpp/container). The `unordered_map` uses hashing if you need constant time element access. – CPlusPlus OOA and D May 17 '14 at 13:07

1 Answers1

0

Usually when you want to do matrix algebra (since you give a link to R I suppose you want to do mathematics with that data) the best is to use a mathematics library. For example if you use eigen library it is very easy to read the matrix. After reading the matrix there are plenty of functions you can apply to these data. (check the benchmarks of this library here http://eigen.tuxfamily.org/index.php?title=Benchmark) Generally speaking if you want to do linear algebra or vector manipulation the best is to use libraries already used/tested/optimized rather to use you own std::vector<> or std::map<> and write your own loops / functions in order to manipulate the data. Your linear algebra code will not be optimized.

#include <iostream>
#include <Eigen/Dense>

int main() {
   Eigen::MatrixXd m(2,3) ;
   m << 1, 2, 3,
        3, 3, 2;
   std::cout << m << std::endl ;
   std::cout << "Transpose of matrix:" << std::endl;
   std::cout << m.transpose() << std::endl;

   return 0 ;
}

You can compile and run it (in my system the library has been installed to /usr/local/include/eigen3/):

$ g++ matrix.cpp  -I /usr/local/include/eigen3/ -o matrix
$ ./matrix 
1 2 3
3 3 2
Transpose of matrix:
1 3
2 3
3 2

For example if you want to transpose this matrix you can do it easily do it with m.transpose() method.

ggia
  • 58
  • 7