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

조회 수: 30 (최근 30일)
Kira Prouse
Kira Prouse 2020년 1월 4일
댓글: Stephen23 2020년 1월 10일
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