MATLAB:将for循环中的标量导出到文本文件

时间:2017-03-03 22:23:08

标签: matlab for-loop writefile

我需要阅读大量文本文件,查找某列的最大值以及相应的时间。找到这些值的for循环工作正常,但我的问题是编写一个文本文件,显示for循环的每次迭代我需要的三个变量(thisfilename,M和wavetime)。

Output_FileName_MaxWaveHeights = ['C:\Users\jl44459\Desktop\QGIS_and_Basement\BASEMENT\Mesh_5_2045\Run_A\','MaxWaveHeights.txt'];
writefile = fopen(Output_FileName_MaxWaveHeights,'a');

dinfo = dir('*.dat');
for K = 1 : length(dinfo)
    thisfilename = dinfo(K).name;  %just the name of the file
    fileID = fopen(thisfilename);  %creates numerical ID for the file name
    thisdata = textscan(fileID,'%f64%f64%f64%f64%f64%f64%f64',500,'HeaderLines',1); %load just this file
    thisdataM = cell2mat(thisdata); %transforms file from cell array to matrix
    [M,I] = max(thisdataM(:,5)); %finds max WSE and row it's in
    wavetime = 2*(I-1); %converts column of max WSE to time
    fprintf(writefile,'%s %8.4f %4.0f \r\n',thisfilename,M,wavetime);
    fclose(fileID); %closes file to make space for next one
end

文本文件最终只给我一次迭代的值,而不是全部。我能够使用displaytable作为解决方法,但后来我写了#34; thisfilename",其中包含非数字字符。

2 个答案:

答案 0 :(得分:0)

虽然我无法使用提供的代码重现问题,但可能的解决方案可能是在循环外写入文件并在之后关闭文件:

Output_FileName_MaxWaveHeights = ['C:\Users\jl44459\Desktop\QGIS_and_Basement\BASEMENT\Mesh_5_2045\Run_A\','MaxWaveHeights.txt'];
writefile = fopen(Output_FileName_MaxWaveHeights,'a');

s = [];
dinfo = dir('*.dat');
for K = 1 : length(dinfo)
    thisfilename = dinfo(K).name;  %just the name of the file
    fileID = fopen(thisfilename);  %creates numerical ID for the file name
    thisdata = textscan(fileID,'%f64%f64%f64%f64%f64%f64%f64',500,'HeaderLines',1); %load just this file
    thisdataM = cell2mat(thisdata); %transforms file from cell array to matrix
    [M,I] = max(thisdataM(:,5)); %finds max WSE and row it's in
    wavetime = 2*(I-1); %converts column of max WSE to time
    s = [s, fprintf(writefile,'%s %8.4f %4.0f \r\n',thisfilename,M,wavetime)];
    fclose(fileID); %closes file to make space for next one
end

fprintf(writefile,s);
fclose(writefile);

答案 1 :(得分:0)

解决了 - 我只是忘了在循环后忘记关闭输出文件。谢谢你的帮助!