Tricks and Tips: Exchanging data between Matlab and C++ in binary format

To save data from C++ in a binary format file, do the following (full worked example to store an array of N double precision real numbers):

#include <fstream>

int main() {

    const int N = 6;

    double *U = (double*)malloc(N * sizeof(double));

    for (int i=0; i<N; i++) U[i] = i;

    std::ofstream outfile;
    outfile.open("file.dat", std::ios::out | std::ios::binary);
    outfile.write((char*)U, N*sizeof(double));
    outfile.close();

    return 0;
}

To load data stored in binary format from Matlab, do the following (full worked example to load an array of N double precision real numbers):

    fd = fopen('file.dat','r');
    U = fread(fd,N,'double');
    fclose(fd);

To save data from Matlab in a binary format file, just launch

    fd = fopen('file.dat','w');
    fwrite(fd,U,'double');
    fclose(fd);

To load data stored in binary format from C++, do the following:

#include <fstream>

int main() {

    const int N = 6;

    double *U = (double*)malloc(N * sizeof(double));

    std::ifstream infile;
    infile.open("file.dat", std::ios::in | std::ios::binary);
    infile.read((char*)U, N*sizeof(double));
    infile.close();

    for (int i=0; i<N; i++) printf("%i %fn", i, U[i]);

    return 0;
}

One thought on “Tricks and Tips: Exchanging data between Matlab and C++ in binary format

  1. George says:

    Hi,
    i’m an undergraduate student,i’m trying to write binary files,but in my case i have a 2D array and i want to read data row per row.
    when i write ascii files in c++, matlab is too slow when it reads:
    c++:
    ofstream offile;
    offile.open(RoPSfilename_full); // for ascii
    //Writting data
    for (int i=0;ipoints.size();i++)
    {
    for(int j=0;j<135;j++)
    {
    //offile<points[i].histogram[j]<<" "; //ascii writting
    }

    offile<<"\n";
    }
    offile.close();

    From matlab i read these data:
    a = fscanf(fid,'%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g',[135 inf]);

    How can i do this with binary files?

    Thanks for your time!
    Your help would be useful!

Leave a Reply

Your email address will not be published. Required fields are marked *