Importing All Files from a specific Folder

조회 수: 80 (최근 30일)
Binay Singh
Binay Singh 2021년 1월 21일
편집: dpb 2021년 1월 21일
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.

채택된 답변

dpb
dpb 2021년 1월 21일
편집: dpb 2021년 1월 21일
datapath=uigetdir([],'Select Data Directory');
d=dir(fullfile(datapath,'*.txt');
for i=1:numel(d)
txt_file = fullfile(datapath,d(i).name);
...
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by