How can I read a binary file with mixed formats in Matlab?

12 次查看(过去 30 天)
I have a binary file with the following formats:
Column 1: char 32
Column 2: float 4
Column 3: integer 4
and I would like to read column by column in Matlab. Each column has about 700 rows of data.
I tried fid = fopen(filename,'rb');
and then used A = fread(fid,Inf,'char') to read the first column, but I've only got numeric data with many more rows than the original text. No success with the following columns either.
Thank you very much for your help.
Claude
  4 个评论
dpb
dpb 2014-4-13
AFAIK this or reading each field sequentially via fread is the only choice in Matlab, Walter? C could build a struct record but not implemented in Matlab.

请先登录,再进行评论。

回答(3 个)

dpb
dpb 2014-4-13
编辑:dpb 2014-4-13
m = memmapfile('file.dat', 'Format', {'uint8, [1 32] 'chdata'; ...
'single' [1 1] 'sdata'; ...
'int32', [1 1] 'idata'});
chdata, sdata, and idata will be in named fields of the structure m.
You'll need to cast the uint8 data for the character data to character via char
doc memmapfile % for more details, of course

Image Analyst
Image Analyst 2014-4-13
Very very easy:
t = readtable(fullFileName);
readtable can handle mixed data types on the same line. Requires R2013b and later.
  5 个评论
dpb
dpb 2014-4-13
编辑:dpb 2014-4-13
Actually, memmapfile is one of the real boons in the upgrade I've come to realize. It would have been a great aid 10-15 yr ago when was still actively consulting.

请先登录,再进行评论。


Claude C.
Claude C. 2014-4-15
It doesn't accept this format, maybe because of the uint8?
  2 个评论
Walter Roberson
Walter Roberson 2014-4-15
It will have to be 'uint8' instead of the 'uint8 accidentally given in the example.
You will probably want to add a 'Repeat', 700 option after 'Format' option.
dpb
dpb 2014-4-15
Doggone, sorry I missed the closing tick...
I'd think he'd want to map the whole file which will by default unless there are known to be precisely N records which seemed to me the "about 700" denies being either known or constant. If there's something else after these records, then that's another potential "gotcha'!", of course.

请先登录,再进行评论。

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by