【发布时间】:2011-10-24 02:54:44
【问题描述】:
Matlab 无法从文件中读取指定数量的元素。我有一个简单的程序,需要读取两个文件,对数据执行线性运算并将组合结果写入第三个文件。
我的问题是:1) 为什么 Matlab 无法读取指定数量的元素,以及 2) 是否有解决方法? 任何你的想法都会有所帮助。
输入文件的一些细节:
- 它们很大 (~18GB)
- 它们的大小相同(完全一样)
程序详情(2-4 以feof 检查两个文件为条件:
- 打开输入和输出文件进行读写(分别)
- 从每个输入文件中读取
N浮点数(N*4 字节) - 对数据执行操作(比如 0.5*(datin1+datin2))
- 将结果写入输出文件。
当然,这一切都非常简单,而且在过去的大多数情况下,这都运作良好。不幸的是,在循环的某个时刻,MATLAB 没有从其中一个文件中获取所有 N 浮点数,并在步骤 3 中给出了矩阵维度错误。
代码片段:
N = 2048;
fidin1 = fopen('file1.dat','r','l');
fidin2 = fopen('file2.dat','r','l');
fidout = fopen('outfile.dat','w','l');
%# I could do some assertions on the file sizes,
%# but I know they are the same size (w/o question).
while(~feof(fidin1) && ~feof(fidin2))
datin1 = fread(fidin1,N,'float=>single',0,'l');
datin2 = fread(fidin2,N,'float=>single',0,'l');
%# the following line produces an error after 100
%# or more iterations in to the procedure
datout = 0.5*(datin1+datin2);
fwrite(fidout,datout,'float',0,'l');
end
更新 1 我收到的错误消息是:
???Error using ==> plus
Matrix dimension must agree.
更新 2
我遵循了一个建议,并在每次阅读后添加了ferrorchecks,神奇地问题就消失了。 所以现在修改我的问题:这里的问题根源可能是什么?这仅仅是时间问题还是错误?
这是更新后的代码片段(仅显示部分代码)。我确信有更好的方法来做到这一点。无论如何,这些检查的添加使 Matlab 能够成功地完成对每个文件的所有读取。
[datin1 count1]= fread(fidin1,N,'float=>single',0,'l');
[msg errn1]=ferror(fidin1);
if errn1
pos1 = ftell(fidin1);
error('Error at Position %d in file. %d bytes were read.',...
pos1,count1);
end
[datin2 count2]= fread(fidin2,N,'float=>single',0,'l');
[msg errn2]=ferror(fidin2);
if errn2
pos2 = ftell(fidin2);
error('Error at Position %d in file. %d bytes were read.',...
pos2,count2);
end
%# the following line produces an error after 100
%# or more iterations in to the procedure
datout = 0.5*(datin1+datin2);
fwrite(fidout,datout,'float',0,'l');
【问题讨论】:
-
您能否包含您收到的确切错误消息?
-
两个文件都在内部硬盘上吗?你在什么操作系统上? 32 位还是 64 位 matlab?
-
@安德鲁,
Error using ==> plus ... Matrix dimensions must agree. -
@Sanjay,它们在同一个内部磁盘上,OS => XP,带有 64b Matlab。我认为这可能与文件大小/文件系统限制有关(我承认这里有点 Windows 无知),但 Matlab 编写文件没有问题。输入文件由 Matlab 编写。
-
在每个 fread() 之后检查 ferror()。那么 [A, count] = fread(...) 并告诉我们有多少元素呢?我猜有一些文件错误,但 Matlab 文档没有说明文件错误后是否将 A 填充到大小 N。