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

30 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-1-4
编辑:Stephen23 2020-1-4
"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 2020-1-4
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.

请先登录,再进行评论。

回答(1 个)

Divya Gaddipati
Divya Gaddipati 2020-1-10
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 个评论
Stephen23
Stephen23 2020-1-10
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);

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by