John W.
John W.

Reputation: 153

Open .gz file with mixed data in MATLAB

I am creating data in a C++ program, writing to a .gz file using the zlib.h library for data compression purposes, and then trying to work with the data in MATLAB. How do I read from the file when it has mixed data?

extern "C"{
#include <zlib.h>
}


#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void){

    //Notes
    //Minute, second, and hour start at zero
    //Day starts at one

    gzFile *fp;
    fp = (gzFile *)gzopen((char *)"measureinput.dat",(char *)"w9");

    int nMe = 1;
    int yr = 1980;
    int mo = 1;
    int dy = 1;
    int hr = 1;
    int mn = 0;
    int se = 0;
    float mlon = 20.0;
    float mlat = 10.0;
    float lshell = 20.0;
    float dens = 10.0;
    float sig = 1.0;
    gzwrite(fp,&nMe,sizeof(int));   
    gzwrite(fp,&yr,sizeof(int));
    gzwrite(fp,&mo,sizeof(int));
    gzwrite(fp,&dy,sizeof(int));
    gzwrite(fp,&hr,sizeof(int));
    gzwrite(fp,&mn,sizeof(int));
    gzwrite(fp,&se,sizeof(int));
    gzwrite(fp,&mlon,sizeof(float));
    gzwrite(fp,&mlat,sizeof(float));
    gzwrite(fp,&lshell,sizeof(float));
    gzwrite(fp,&dens,sizeof(float));
    gzwrite(fp,&sig,sizeof(float));

    gzclose(fp);
}

Upvotes: 1

Views: 749

Answers (1)

A. Donda
A. Donda

Reputation: 8477

You can read binary data in Matlab using fread. For this however, the data can't be compressed – unless you implement the decompression in Matlab, too. If the only purpose of writing the data is to be read into Matlab, it therefore doesn't make sense to use gzip. The same holds if you follow kyamagu's recommendation to use a text format; it can't be read in compressed form, either.

Matlab's own binary format, the MAT-file, does support compression (at least in recent versions). If compression is important to you, you therefore might consider writing a MAT-file from your C++ code. The format is documented at http://www.mathworks.de/help/pdf_doc/matlab/matfile_format.pdf. Moreover, http://www.mathworks.de/help/pdf_doc/matlab/apiext.pdf describes a C / C++ / Fortran library that supports writing MAT-files and which comes with Matlab.

Upvotes: 1

Related Questions