How to open files based on information from another file?
2 ビュー (過去 30 日間)
古いコメントを表示
I have a .txt file with 7 columns and thousands of rows, as follows:
20140101 2240 140213 -5.543 -34.973 32.4 2000
20140101 2250 118094 -4.475 -35.372 28.2 2000
20140101 1930 196279 -6.136 -33.958 24.2 3000
20140101 0000 178273 -6.082 -34.284 25.8 4000
20140101 1600 238772 -6.073 -33.188 28.4 6000
20140102 2340 86399 -7.214 -35.951 26.0 15000
I need to open the other files according to the strings in column 1, 2 and 7. That is, the files would have the following structure:
precip_CZ_$column7_$column1_$column2.dat
For example, this is the file name:
precip_CZ_02000_20140101_2240.dat
precip_CZ_02000_20140101_2250.dat
precip_CZ_03000_20140101_1930.dat
precip_CZ_04000_20140101_0000.dat
precip_CZ_06000_20140101_1600.dat
precip_CZ_15000_20140102_2340.dat
2 件のコメント
stozaki
2020 年 9 月 20 日
Hello pink flower,
Does the "precip_CZ_02000_20140101_2240.dat" file contain 140213 -5.543 -34.973 32.4 as data?
stozaki
採用された回答
Ameer Hamza
2020 年 9 月 20 日
Try this
f = fopen('data.txt');
data = textscan(f, '%f %f %f %f %f %f %f');
fclose(f);
data = [data{:}];
filenames = compose('precip_CZ_%05d_%08d_%04d.dat', data(:,7), data(:,1), data(:,2))
output
>> filenames
filenames =
6×1 cell array
{'precip_CZ_02000_20140101_2240.dat'}
{'precip_CZ_02000_20140101_2250.dat'}
{'precip_CZ_03000_20140101_1930.dat'}
{'precip_CZ_04000_20140101_0000.dat'}
{'precip_CZ_06000_20140101_1600.dat'}
{'precip_CZ_15000_20140102_2340.dat'}
Read these .dat files using load(), readmatrix() or other similar functions.
2 件のコメント
Ameer Hamza
2020 年 9 月 20 日
fopen() itself is not important. The correct method depends on how the data is present in your .dat file.
その他の回答 (1 件)
Walter Roberson
2020 年 9 月 20 日
data = load('YourFile.txt');
filenames = "precip_CZ_" + data(:,7) + "_" + data(:,1) + "_" + data(:,2) + ".dat";
nfiles = numel(filenames);
for K = 1 : nfiles
thisfile = filenames(K);
[fid, msg] = fopen(thisfile);
if fid < 0
fprintf('Error opening file "%s" because "%s"\n', thisfile, msg);
continue
end
do something
fclose(fid)
end
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!