C++ code for reading unknown size matrix from text file

C++ code for reading unknown size matrix from text file

In this post, I upload my program {C++ code for reading unknown size matrix from text file } <download> which imports an arbitrary size matrix (or 2D array) from text (txt) file. This is c++ code.

The below is an execution result. The first figure is a text file including a matrix, the next figure is an execution screen. It’s very easy to use.

xtxt

text file to import. It has an arbitrary size matrix

screen

execution screen image, it imported the matrix from the above text fileSometimes, we want to import a matrix that we don’t know its size, especially when the file was generated from other programs.

I had googled for long time, and I realized that it is not easy to find. So, I made.

You don’t need to indicate the size of matrix, (cols and rows). It automatically imports and outputs, double type vector,  column and row size. It is very easy to use, and you can download the source code from here  <download>.

The only thing you should do is just download the source code, and import “x.txt” or “y.txt” which includes an arbitrary matrix.

Enjoy my program { C++ code for reading unknown size matrix from text file } Then good luck.

I referred partially this site.

http://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-into-integers

—————————————————————————————————————————–

I am Youngmok Yun, and writing about robotics theories and my research.

My main site is http://youngmok.com, and Korean ver. is  http://yunyoungmok.tistory.com.

—————————————————————————————————————————–

6 thoughts on “C++ code for reading unknown size matrix from text file

  1. Andreia Moco

    Hi Youngmok, Thank you very much for making your {C++ code for reading unknown size matrix from text file} available. As you stated, it is very easy to use and is also easy to adapt if one needs Eigen’s MatrixXd as output. I tested your code with matrixes of different sizes < 1000 x 1000 and it is robust for this range.

    Reply
  2. Ammar

    Hello Youngmok, thanks for your code. it really helps me. But, can you explain how to convert your 2D vector into 2D array (array of matrix)?

    Reply
  3. Ryan

    Hello Youngmok, thank you so much for this. However, I seem to get an error in line 51 with the “==” operator. Would love to get your help on this. Thank you!

    Reply
    1. Joseph

      Hi Ryan, I ran into the same problem. If you replace line 51 with the following, then it should work:

      if (!getline(file_X, line)) break;

      Reply
      1. admin Post author

        Thanks for your kind feedback. I have updated the download file. I guess it is a problem of compilers. Different toolchains sometimes show a picky result.

        Reply

Leave a Reply