Having trouble importing data from file with same name in different folders

2 views (last 30 days)
I am trying to import data from multiple participants in MatLab. I think I am having trouble because the file names that are being imported are all the same but are under different directories. I have used fullfile to find all these file names and place them into the structure but when I am trying to import the data, I end up having repeats in each of the columns. I think this is due to the file names being similar. Here is some sample code.
totalFiles=dir(fullfile(mydir, 'pt*','scan*', 'data.txt'));
numTotalFiles=length(totalFiles);
for i=1:numTotalFiles
filename = [totalFiles(i).name] ; % all of the totalFiles(i).name = data.txt (but placed in different directories)
num2 = importdata(filename, ' ', 131); % hidata starts at line 131
hidata = num2.data;
alldata (:,i) = hidata (:,1); % all of columns end up being the same as totalfiles(1).name rather than totalfiles(i).name
end

Accepted Answer

Voss
Voss on 16 Jun 2022
Use fullfile with the folder field of totalFiles to construct the full-path name of each file:
totalFiles=dir(fullfile(mydir, 'pt*','scan*', 'data.txt'));
numTotalFiles=length(totalFiles);
for i=1:numTotalFiles
% filename = [totalFiles(i).name] ; % all of the totalFiles(i).name = data.txt (but placed in different directories)
filename = fullfile(totalFiles(i).folder,totalFiles(i).name);
num2 = importdata(filename, ' ', 131); % hidata starts at line 131
hidata = num2.data;
alldata (:,i) = hidata (:,1); % all of columns end up being the same as totalfiles(1).name rather than totalfiles(i).name
end

More Answers (0)

Categories

Find more on File Name Construction in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!