Matlab 无法从文件中读取指定数量的元素。我有一个简单的程序,需要读入两个文件,对数据执行线性运算并将组合结果写入第三个文件。
我的问题是:1) 为什么 Matlab 无法读取指定数量的元素以及 2) 是否有解决方法? 任何您的想法都会有所帮助。
输入文件的一些细节:
- 它们很大 (~18GB)
- 它们的尺寸(完全一样)
有关过程的详细信息(2-4 取决于对两个文件的 feof
检查:
- 打开输入和输出文件进行读写(resp.)
- 从每个输入文件中读入
N
个 float (N*4 字节) - 对数据执行操作(比如 0.5*(datin1+datin2))
- 将结果写入输出文件。
诚然,这一切都非常简单,并且在过去的大多数情况下都运行良好。不幸的是,在循环的某个时刻,MATLAB 没有从其中一个文件中获取所有 N
float ,并在第 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
我听从了一个建议,并在每次读取后加入了 ferror
检查,神奇地 问题就消失了。 那么现在修改我的问题:这里问题的根源可能是什么?这仅仅是时间问题还是错误?
这是更新后的代码片段(仅显示部分代码)。我相信有更好的方法可以做到这一点。无论如何,添加这些检查允许 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');
最佳答案
你有没有在错误发生时专门查看datin1和datin2变量?尝试转到“调试-->如果出现错误/警告则停止...”,然后选择“如果出错则始终停止(如果出错则停止)”。运行您的程序,一旦它崩溃,请查看 datin1 和 datin2。希望这能解释为什么将它们加在一起现在有效。
关于matlab - 为什么 MATLAB 无法成功读取二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7011858/