了解 MATLAB/Ocatave 文件读取
Understanding MATLAB/Ocatave file reading
下面是读取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?
根据代码,tvec
(从文件中读取的数据)已知为 cnt x 784
,而 cnt
未知。您粘贴的行解决了 cnt
.
由于上一行导致文件指针指向文件末尾,ftell(fid)
将告诉文件中的当前位置,在这种情况下对应于文件中的总字节数。然后他们减去 16,因为前 16 个字节显然不是感兴趣数据的一部分。现在,我们知道 cnt * 784 = ftell(fid) - 16
所以要求解 cnt
我们只需要除以 784
.
接下来的几行将文件指针移回第 17 个字节(数据的开头),然后循环遍历 1:cnt
,然后用 [=19= 读入每个 784 字节的片段].
下面是读取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?
根据代码,tvec
(从文件中读取的数据)已知为 cnt x 784
,而 cnt
未知。您粘贴的行解决了 cnt
.
由于上一行导致文件指针指向文件末尾,ftell(fid)
将告诉文件中的当前位置,在这种情况下对应于文件中的总字节数。然后他们减去 16,因为前 16 个字节显然不是感兴趣数据的一部分。现在,我们知道 cnt * 784 = ftell(fid) - 16
所以要求解 cnt
我们只需要除以 784
.
接下来的几行将文件指针移回第 17 个字节(数据的开头),然后循环遍历 1:cnt
,然后用 [=19= 读入每个 784 字节的片段].