フィルターのクリア

constructing file identifier from string?

2 ビュー (過去 30 日間)
Joseph Koval
Joseph Koval 2018 年 7 月 16 日
回答済み: KSSV 2018 年 7 月 16 日
I open several files, write text to the files upon opening them...for example...
fullfileKBDR = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KBDR_',forecastyears(k,:),'.csv')
fileID1 = fopen(fullfileKBDR, 'w')
fprintf(fileID1,formatSpec)
fullfileKMHT = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KMHT_',forecastyears(k,:),'.csv')
fileID2 = fopen(fullfileKMHT, 'w');
fprintf(fileID2,formatSpec)
fullfileKASH = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KASH_',forecastyears(k,:),'.csv')
fileID3 = fopen(fullfileKASH, 'w');
fprintf(fileID3,formatSpec)
fullfileKPWM = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KPWM_',forecastyears(k,:),'.csv')
fileID4 = fopen(fullfileKPWM, 'w');
fprintf(fileID4,formatSpec)
But the question is that later in the code, I have a loop where I'm processing data in the loop. I want to be able to construct the file identifier (e.g. fileID1, fileID2, fileID3, fileID4) and write to the file based on the loop counter. So something that would like this, but it doesn't work:
for n = 1:4
%Do stuff
nasstr = string(n)
fileident = strcat('fileID',nasstr)
fprintf(fileident, 'blah\n')
end
Can someone share the syntax that would make this work? Thanks.

採用された回答

KSSV
KSSV 2018 年 7 月 16 日
You can initialize file identifiers as an array, and use them in loop.
fullfileKBDR = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KBDR_','.csv')
fid(1) = fopen(fullfileKBDR, 'w')
fprintf(fileID1,formatSpec)
fullfileKMHT = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KMHT_','.csv')
fid(2) = fopen(fullfileKMHT, 'w');
fprintf(fileID2,formatSpec)
fullfileKASH = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KASH_','.csv')
fid(3) = fopen(fullfileKASH, 'w');
fprintf(fileID3,formatSpec)
fullfileKPWM = strcat('/Users/jkoval/Documents/MATLAB/archived_fod_forecasts/output/KPWM_','.csv')
fid(4) = fopen(fullfileKPWM, 'w');
fprintf(fileID4,formatSpec)
for n = 1:4
%Do stuff
nasstr = string(n)
fid(n) % this gives file identifier
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by