Search code examples
c++matlabmatrixbinaryfileseigen

Save a Matrix in Matlab to a bin file and read it in c++


I saved an integer 10x10 matrix I in Matlab into a binary file using fwrite:

fid = fopen('True.bin' , 'w');
fwrite(fid , I , 'int');
fclose(fid)

Now when I try to open it in C++ using fstream library, it returns an error. The C++ code is as follows:

int IMG_SIZE = 10;
char * buffer;
long size = IMG_SIZE * IMG_SIZE;
ifstream file ("True.bin", ios::in|ios::binary|ios::ate);
buffer = new char [size];
file.read (buffer, size);
file.close();

Any idea how to load the file into an array, or Eigen matrix of type MatrixXi ?

Thanks


Solution

  • When you write values using the 'int' value for the precision argument to fwrite, it writes them as 4-byte integers, so your 10x10 matrix will take up 10x10x4 = 400 bytes. But you are only allocating a buffer that is 10x10 = 100 bytes long.