Reading multiple precision binary files through fread in Matlab

▼魔方 西西 提交于 2019-11-27 06:13:15

问题


I have a huge binary file which has records with multiple precision as {'Double','Double', 'Int32','Int8','Char'}. I have used memmapfile to read in the data but its painfully slow to read in the data. Is there a way to read the whole file through fread?


回答1:


You can use the 'skip' option of the FREAD function as well as FSEEK to read the records one "column" at-a-time:

%# type and size in byte of the record fields
recordType = {'double' 'double' 'int32' 'int8' 'char'};
recordLen = [8 8 4 1 1];
R = cell(1,numel(recordType));

%# read column-by-column
fid = fopen('file.bin','rb');
for i=1:numel(recordType)
    %# seek to the first field of the first record
    fseek(fid, sum(recordLen(1:i-1)), 'bof');

    %# % read column with specified format, skipping required number of bytes
    R{i} = fread(fid, Inf, ['*' recordType{i}], sum(recordLen)-recordLen(i));
end
fclose(fid);

This code should work for any binary records file in general, you just have to specify the data types and byte length of the records fields. The result will be returned in a cell array containing the columns.



来源:https://stackoverflow.com/questions/8096702/reading-multiple-precision-binary-files-through-fread-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!