Home > Software engineering >  Binary files: write with C , read with MATLAB
Binary files: write with C , read with MATLAB

Time:07-29

I could use your support on this. Here is my issue:

I've got a 2D buffer of floats (in a data object) in a C code, that I write in a binary file using:

ptrToFile.write(reinterpret_cast<char *>(&data->array[0][0]), nbOfEltsInArray * sizeof(float));

The data contains 8192 floats, and I (correctly ?) get a 32 kbytes (8192 * 4 bytes) file out of this line of code.

Now I want to read that binary file using MATLAB. The code is:

hdr_binaryfile = fopen(str_binaryfile_path,'r');
res2_raw = fread(hdr_binaryfile, 'float');
res2 = reshape(res2_raw, int_sizel, int_sizec);

But it's not happening as I expect it to happen. If I print the array of data in the C code using std::cout, I get:

pCarte_bin->m_size = 8192
pCarte_bin->m_sizel = 64
pCarte_bin->m_sizec = 128
pCarte_bin->m_p[0][0] = 1014.97
pCarte_bin->m_p[0][1] = 566946
pCarte_bin->m_p[0][2] = 423177
pCarte_bin->m_p[0][3] = 497375
pCarte_bin->m_p[0][4] = 624860
pCarte_bin->m_p[0][5] = 478834
pCarte_bin->m_p[1][0] = 2652.25
pCarte_bin->m_p[2][0] = 642077
pCarte_bin->m_p[3][0] = 5.33649e 006
pCarte_bin->m_p[4][0] = 3.80922e 006
pCarte_bin->m_p[5][0] = 568725

And on the MATLAB side, after I read the file using the little block of code above:

size(res2) = 64  128
res2(1,1) = 1014.9659
res2(1,2) = 323288.4063
res2(1,3) = 2652.2515
res2(1,4) = 457593.375
res2(1,5) = 642076.6875
res2(1,6) = 581674.625
res2(2,1) = 566946.1875
res2(3,1) = 423177.1563
res2(4,1) = 497374.6563
res2(5,1) = 624860.0625
res2(6,1) = 478833.7188

The size (lines, columns) is OK, as well as the very first item ([0][0] in C == [1][1] in MATLAB). But:

  1. I'm reading the C line elements along the colomns: [0][1] in C == [1][2] in MATLAB (remember that indexing starts at 1 in MATLAB), etc.
  2. I'm reading one correct element out of two along the other dimension: [1][0] in C == [1][3] in MATLAB, [2][0] == [1][5], etc.

Any idea about this ?

Thanks! bye

CodePudding user response:

Leaving aside the fact there seems to be some precision difference (likely the display settings in MATLAB) the issue here is likely the difference between row major and column major ordering of data. Without more details it will be hard to be certain. In particular MATLAB is column major meaning that contiguous memory on disk is interpreted as detailing sequential elements in a column rather than a row.

The likely solution is to reverse the two sizes in your reshape, and access the elements with indices reversed. That is, swap the int_size1 and int_size2, and then read elements expecting

pCarte_bin->m_p[0][0] = res2(1,1)
pCarte_bin->m_p[0][1] = res2(2,1)
pCarte_bin->m_p[0][2] = res2(3,1)
pCarte_bin->m_p[0][3] = res2(4,1)
pCarte_bin->m_p[1][0] = res2(1,2)

etc.

You could also transpose the array in MATLAB after read, but for a large array that could be costly in itself

  • Related