MATLAB: How to import multiple (147) text files in Matlab

text filetopotoolbox

Hi all,
I have 147, comma-delimited, text files of precipitation data taken from 147 weather stations in Cumbria, which I intend to use to create a hydrological model, along with a DEM, land use maps and river discharge data using mainly TopoToolbox. I tried a few different methods which get me so far but seem to fall short.
For example:
%% Method 1
p = ('*.txt');
for i = 1:nume1(p)
Rain = dlmread(p(i).name);
end
rain = uigetfile('*.txt','MultiSelect','on');
%% Method 2
[files,path] = uigetfile('*.txt','MultiSelect','on');
if iscell(files)
for n = 1:length(files)
data = importdata(fullfile(path,files{n})); % fullfile including path
% save data

end
else
data = importdata(fullfile(path,files));
% save data
end
%% Method 3
[filenames, pathname] = uigetfile('*.txt''MultiSelect', 'on');
filenames = cellstr(filenames); % EDITED

for n = 1:length(filenames)
afile = fullfile(pathname, filenames{n}); % EDITED
data = importdata(afile);
% Remove the file extension file the name:
[dummy, afilename] = fileparts(filenames{n});
save(afilename, 'data');
end
The text files are formatted, column 1) site id, column 2) MATLAB datenumber and column 3) daily rainfall total, with no headings. I aim to extract November and December from 1990, 2000, 2007 and 2015 which I can then interplote to include as weightings for flow accumulation plots using TopoToolbox if possible.
I'm using (R2019b).

Best Answer

method 3 should be
[filenames, pathname] = uigetfile('*.txt','MultiSelect', 'on');
after defenition of formatSpec, delimiter, startRow and data = cell(1,length(files));, I would use within the loop:
fileID = fopen(fullfile(path,filenames{n}),'r','n','UTF-8');
fseek(fileID, 0, 'bof');
data{a} = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'EmptyValue', 0, 'HeaderLines' ,startRow, 'ReturnOnError', false, 'EndOfLine', '\r\n');
fclose(fileID);
its way fatster to skip header of tables (startRow = 1;) and import numbers as number (%f), then import the whole colum and convert numbers using str2num later.
Related Question