How to load multiple .txt files into the workspace at once

47 views (last 30 days)
So I'm currently loading each .txt file individually by editing the function and running it.
function data1994=load_tide_data(filename)
data1994.filename=filename;
fid=fopen(filename);
for I=1:12
tmpl=fgetl(fid);
end
J=1;
while ischar(tmpl)
tmp=textscan(tmpl,'%s %s %s %s %s')
data.t(J)=datenum([ cell2mat(tmp{2}) ' ' cell2mat(tmp{3}) ]);
tmph=str2num(cell2mat(tmp{4}));
if isempty(tmph)
tmph=NaN;
end
data.h(J)=tmph;
tmpl=fgetl(fid);
J=J+1;
end
fclose(fid);
The files go from 1993 to 2013 in the same format (1993LOW.txt etc) I'm guessing I have to create a funtion for it to run through all the files at once but I have no idea how to do this as I'm a matlab rookie. Any advice would be much appreciated.
  2 Comments
Stephen23
Stephen23 on 4 Jan 2020
Edited: Stephen23 on 4 Jan 2020
"So I'm currently loading each .txt file individually by editing the function and running it."
What specifically needs to be changed for each file? Why not just call exactly the same function with each different filename?
"I'm guessing I have to create a funtion for it to run through all the files at once but I have no idea how to do this..."
A simple script would be enough. Just follow the examples in the documentation:
Note that only the first line of your functions really does anything useful, as none of the other data is returned or used in any way, and it is simply discarded when the function returns.
Image Analyst
Image Analyst on 4 Jan 2020
Needs to be
function data = load_tide_data(filename)
data.filename = filename;
% Now the rest of the code to read in file and assign the "data" variable.
end
so you return the right thing.

Sign in to comment.

Answers (1)

Divya Gaddipati
Divya Gaddipati on 10 Jan 2020
Following is a small example:
files = dir(fullfile(filedir, '*.txt'));
n = length(files);
data = cell(n);
for i = 1 : n
fid = fopen(fullfile(filedir, files(i).name));
data{i} = fscanf(fid,'%s %s %s %s %s');
fclose(fid);
end
Alternatively, you can also use importdata instead of fopen, fscanf and fclose.
For more information, you can refer to the following links:
Hope this helps!
  1 Comment
Stephen23
Stephen23 on 10 Jan 2020
Note that
data = cell(n);
will result in a square cell array of size nxn, of which only the first column will be used by this code. This seems rather inefficient. Perhaps the author intended to write:
data = cell(1,n);

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!