How to open files based on information from another file?

4 Ansichten (letzte 30 Tage)
pink flower
pink flower am 20 Sep. 2020
Kommentiert: Ameer Hamza am 20 Sep. 2020
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 Kommentare
stozaki
stozaki am 20 Sep. 2020
Hello pink flower,
Does the "precip_CZ_02000_20140101_2240.dat" file contain 140213 -5.543 -34.973 32.4 as data?
stozaki

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 20 Sep. 2020
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 Kommentare
pink flower
pink flower am 20 Sep. 2020
This worked for me. Thanks! How can I use fopen?
Ameer Hamza
Ameer Hamza am 20 Sep. 2020
fopen() itself is not important. The correct method depends on how the data is present in your .dat file.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 20 Sep. 2020
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

Community Treasure Hunt

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

Start Hunting!

Translated by