Importing All Files from a specific Folder

79 vues (au cours des 30 derniers jours)
Binay Singh
Binay Singh le 21 Jan 2021
Modifié(e) : dpb le 21 Jan 2021
Hello,
I have a few hundred text files in a folder, and I want to import and organize all of them within MATLAB. The files are all the same format, but each indivdual file is unique in representing a specifc subject and day of an experiment. For previous analysis of each file I have been using this code to format and organize the data into a structure within MATLAB:
clear
clc
[file, path] = uigetfile('*.txt','Choose Subject 1','default.txt');
txt_file = fullfile(path,file);
[fid,msg] = fopen(txt_file,'rt');
assert(fid>=3,msg)
out = struct();
while ~feof(fid)
pos = ftell(fid);
str = strtrim(fgetl(fid));
if numel(str)
spl = regexp(str,':','once','split');
spl = strtrim(spl);
if isnan(str2double(spl{1}))
fnm = strrep(spl{1},' ','');
val = str2double(spl{2});
if isnan(val)
out.(fnm) = spl{2};
else
out.(fnm) = val;
end
else
fseek(fid,pos,'bof');
vec = fscanf(fid,'%*d:%f%f%f%f%f',[1,Inf]);
out.(fnm) = vec;
end
end
end
fclose(fid);
Subject1 = out;
clearvars -except Subject1
I was wondering if there was a way to create a loop where the code would run through however many files are in my folder and organize each file into their own structure array? I attached 3 example files, but they are not within a single folder. I am specifcally looking for help creating a loop that would go through an entire folder of these files without manually clicking on each file. Any assitance is really apprecaited, thanks.

Réponse acceptée

dpb
dpb le 21 Jan 2021
Modifié(e) : dpb le 21 Jan 2021
datapath=uigetdir([],'Select Data Directory');
d=dir(fullfile(datapath,'*.txt');
for i=1:numel(d)
txt_file = fullfile(datapath,d(i).name);
...
end

Plus de réponses (0)

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by