了解MATLAB / Ocatave文件读取

时间:2016-12-06 17:47:59

标签: matlab octave filereader

以下是阅读MNIST data files的专用函数。

function [tlab, tvec] = readmnist(datafn, labelfn)
% function reads mnist data and labels 

fid = fopen(datafn, 'rb');
//open datafn in read and big-endian format.
//returns a file-id
if fid==-1
   error('Error opening data file');
end;

fseek(fid, 0, 'eof');
// Seek to the 0th byte from the end of the file.
// In other words. Just go to the end of the file.
// fid == the file to be accessed.
// 'eof' == relative position.
// 0 == bytes to be read.

cnt = (ftell(fid) - 16)/784;

fseek(fid, 16, 'bof');
//Move to the 16th byte from the beginning of file.
tvec = zeros(cnt, 784);
//returns a 2D cntx784 matrix of zeros.

for i=1:cnt
   im = fread(fid, 784, 'uchar');
   tvec(i,:) = (im(:)/255.0)';
end;
fclose(fid);
cnt

fid = fopen(labelfn, 'rb');
if fid==-1
   error('Error opening label file');
end;
fseek(fid, 8, 'bof');
[tlab nel] = fread(fid, cnt, 'uchar');
if nel ~= cnt 
   disp('Not all elements read.');
end;
fclose(fid);
nel

你能告诉我下一行有什么问题吗?

cnt = (ftell(fid) - 16)/784;

这里发生了什么?什么是784?

1 个答案:

答案 0 :(得分:3)

根据代码,tvec(从文件中读取的数据)已知为cnt x 784cnt未知。您粘贴的行已解决cnt

由于前一行导致文件指针指向文件的末尾,ftell(fid)将告诉文件中的当前位置,在这种情况下,该位置对应于文件中的总字节数。然后他们减去16,因为显然前16个字节不是感兴趣的数据的一部分。现在,我们知道cnt * 784 = ftell(fid) - 16所以要解决cnt我们只需要除以784

然后,以下行将文件指针移回第17个字节(数据的开头),然后循环遍历1:cnt,然后使用fread读取每个784字节的片段。