MATLAB Answers

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

4 ビュー (過去 30 日間)
Kira Prouse
Kira Prouse 2020 年 1 月 4 日
コメント済み: Stephen Cobeldick 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 件のコメント

Stephen Cobeldick
Stephen Cobeldick 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.

サインイン to comment.

回答 (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 件のコメント

Stephen Cobeldick
Stephen Cobeldick 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);

サインイン to comment.

サインイン してこの質問に回答します。


Translated by