2017-03-03 155 views
1

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

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作为解决方法,但是在编写包含非数字字符的“thisfilename”时遇到问题。

+0

如何将值保存到单元格中并将单元格写入for循环外部的文件? – NKN

+0

我没有看到你在循环结束后关闭输出文件'fclose(writefile)'。你忘了把它包含在例子中吗? – Hoki

回答

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); 
0

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