2016-12-06 35 views
1

以下是專用函數來讀取MNIST data files瞭解MATLAB/Ocatave文件讀數

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?

回答

3

根據代碼tvec(正在從文件讀入的數據)已知爲cnt x 784cnt未知。你粘貼的線路解決了cnt

由於上一行導致文件指針指向文件末尾,因此ftell(fid)會告訴文件中當前位置,在這種情況下,該位置與文件中的總字節數相對應。然後他們減去16,因爲顯然前16個字節不是感興趣的數據的一部分。現在,我們知道cnt * 784 = ftell(fid) - 16所以要解決cnt我們只需要除以784

接下來的行然後將文件指針移回第17個字節(數據的開始),然後循環通過1:cnt,然後在每個784字節的塊中使用fread讀取。