How to load multiple .txt files into the workspace at once
45 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Stephen23
el 4 de En. de 2020
Editada: Stephen23
el 4 de En. de 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
el 4 de En. de 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.
Respuestas (1)
Divya Gaddipati
el 10 de En. de 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 comentario
Stephen23
el 10 de En. de 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);
Ver también
Categorías
Más información sobre Get Started with MATLAB en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!