Importing All Files from a specific Folder

83 views (last 30 days)
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.

Accepted Answer

dpb
dpb on 21 Jan 2021
Edited: dpb on 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

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!