Matlab,fread,加速读取具有多种数据类型和多种采样率的文件

时间:2015-10-02 14:07:37

标签: matlab

使用Matlab R2015a。我正在使用fread从二进制文件中读取传感器数据。数据包含多个精度。一个信号以其他信号速率的5倍采样。该文件被构造为一系列批次,其中每批具有例如批次。 1个signal_A样本,但是5个signal_B样本。

我已经搜索了关于如何快速加载和格式化数据的示例,但我看到的解决方案仅代表单一采样率的情况,使解决方案更简单,据我所知。

我想避免使用for - 循环,这很慢。请参阅下文,了解数据在文件中的排列方式,以及我现在所拥有的简单代码示例。

有关如何提高速度的任何建议吗?

File structure

clear;
fid = fopen('binaryFile.bin','r');
signal_B = [];

numBatches = Inf; % read all
batchSize = 17; % each batch takes up 17 bytes

% PART 1 (everything that is not signal_B)
batchSerialNumber = fread(fid, numBatches, '*uint32', batchSize-4);
fseek(fid, 4, 'bof'); % rewind
signal_A = fread(fid, numBatches, '*uint16', batchSize-2);
fseek(fid, 6, 'bof'); % rewind
misc_info = fread(fid, numBatches, '*uint8', batchSize-1);

% PART 2 (signal_B)
for i = 1:length(batchSerialNumber)
    fseek(fid, ((i-1)*batchSize) + 7, 'bof'); % set position in file, according to batch number (i)
    signal_B = [signal_B; fread(fid, 5, '*int16')]; % read the 5 samples of signal_B in this batch
end

1 个答案:

答案 0 :(得分:1)

更多谷歌搜索和一个很好的解决方案最终出现...比使用for循环快约100倍。

clear;
fid = fopen('binaryFile.bin','r');

numBatches = Inf; % read all
batchSize = 17; % each batch takes up 17 bytes

% PART 1 (everything that is not signal_B)
batchSerialNumber = fread(fid, numBatches, '*uint32', batchSize-4);
fseek(fid, 4, 'bof'); % rewind
signal_A = fread(fid, numBatches, '*uint16', batchSize-2);
fseek(fid, 6, 'bof'); % rewind
misc_info = fread(fid, numBatches, '*uint8', batchSize-1);
fseek(fid, 7, 'bof'); % rewind

% PART 2 (signal_B)
signal_B_line_1 = fread(fid, numBatches, '*int16', batchSize-2);
fseek(fid, 9, 'bof');
signal_B_line_2 = fread(fid, numBatches, '*int16', batchSize-2);
fseek(fid, 11, 'bof');
signal_B_line_3 = fread(fid, numBatches, '*int16', batchSize-2);
fseek(fid, 13, 'bof');
signal_B_line_4 = fread(fid, numBatches, '*int16', batchSize-2);
fseek(fid, 15, 'bof');
signal_B_line_5 = fread(fid, numBatches, '*int16', batchSize-2);

signal_B(length(batchSerialNumber)*5,1) = int16(0);

signal_B(1:5:end,1) = signal_B_line_1;
signal_B(2:5:end,1) = signal_B_line_2;
signal_B(3:5:end,1) = signal_B_line_3;
signal_B(4:5:end,1) = signal_B_line_4;
signal_B(5:5:end,1) = signal_B_line_5;