2017-03-03 73 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

解決 - 它只是我忘了關閉循環後的輸出文件。謝謝您的幫助!