Reading raw data in Matlab

One of the most common things I do in Matlab almost always involves reading in binary data.  For a few years I went through the typical [cci lang="matlab"]fp=fopen(‘filename.dat’…[/cci].  After typing the fopen, fread, reshape and fclose too many times, I finally made it into an all-in-one Matlab function called [cci lang="matlab"]readraw()[/cci] which will do all the reading and reformatting in one function call.

[cc lang="matlab"]
function [d] = readraw(filename, type, ds, endian)

if( nargin == 3 )
endian = ‘b’;
end

fp=fopen(filename, ‘rb’, endian);
d = fread(fp, prod(ds), type);
fclose(fp);

d = reshape(d, ds);
[/cc]

There isn’t much magic here, just a simple idea that I use almost daily.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>