Matlab无法从文件中读取指定数量的元素.我有一个简单的程序,需要读取两个文件,对数据执行线性操作,并将组合结果写入第三个文件.
我的问题是:1)为什么Matlab无法读取指定数量的元素,2)是否有解决方法?你的任何想法都会有所帮助.
输入文件的一些细节:
有关程序的详细信息(2-4以feof检查两个文件为条件:
N从每个输入文件中读取浮点数(N*4个字节)当然,这一切都非常简单,在过去的大多数情况下,这都运作良好.不幸的是,在循环中的某个时刻,MATLAB没有N从其中一个文件中获取所有浮点数,并在步骤3中给出了矩阵维度错误.  
代码SNIP:
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
Run Code Online (Sandbox Code Playgroud)
更新1 我收到的错误消息是:
???Error using ==> plus
Matrix dimension must agree.
Run Code Online (Sandbox Code Playgroud)
更新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');
Run Code Online (Sandbox Code Playgroud)
    您是否在错误发生时专门查看过 datin1 和 datin2 变量?尝试转到“调试-->如果出现错误/警告则停止...”,然后选择“如果出现错误则始终停止(如果出现错误则停止)”。运行你的程序,一旦它崩溃,查看datin1和datin2。希望这能解释为什么将它们添加在一起现在可以发挥作用。