Write Binary File In C++ And Read In MATLAB

Following this post, I’m able to write binary file in C++ to pass data to MATLAB.

In C++, I have a cv::Mat matFloats of type float, I used the following code to store the data in a binary file.

#include <fstream>

ofstream outfile;
outfile.open("data.dat", std::ios::out | std::ios::binary);
outfile.write((char*)matFloat.data, 2 * contourCentered.size() * sizeof(float));
outfile.close();

And the following code in MATLAB reads the data and reshapes the array.

fd = fopen('data.dat', 'r');
matFloat = fread(fd, 'float');
fclose(fd);

matFloat = reshape(matFloat, 2, []);