Pull together files of the same name from different folders
Show older comments
I am reading in several files of the same name from all different folders based on the folder name. Here I have gathered a list of the paths for these files:
axialList = dir('*_A_*');
for i = 1:length(axialList)
folders{i} = strcat(axialList(i).folder,axialList(i).name);
end
for i = 1:length(folders)
axialFiles{i} = strcat(folders{i},'\specimen.dat');
end
This gives me cells with all the file paths I want to read. Then I'm trying to put these names in a loop to read it. This worked before I put it in the loop:
FormatString = repmat('%f',1,7);
for i = 1:length(axialFiles)
fileID = fopen(axialFiles{i});
SortHeader = textscan(fileID,'%s',5,'delimiter','\n');
Data{i} = textscan(fileID,FormatString,'delimiter','\t');
Data{i} = cell2mat(Data{i});
fclose(fileID)
end
Now that I have it reading in fileID in the loop, I get the error 'Invalid file identifier. Use fopen to generate a valid file identifier'. If instead I just put the file names in like here:
FormatString = repmat('%f',1,7);
for i = 1:length(axialFiles)
% fileID = fopen(axialFiles{i});
SortHeader = textscan(axialFiles{i},'%s',5,'delimiter','\n');
Data{i} = textscan(axialFiles{i},FormatString,'delimiter','\t');
Data{i} = cell2mat(Data{i});
% fclose(fileID)
end
I get an empty cell array. Please help!
Accepted Answer
More Answers (1)
I recommend that you use fullfile rather than concatenating strings, and that you explicitly preallocate the cell arrays before the loops.
S = dir('*_A_*');
X = [S.isdir];
assert(any(X),'No folders matched the DIR search pattern: fix the pattern!')
F = {S(X).name}; % only folders
P = {S(X).folder};
N = numel(F);
D = cell(1,N);
fmt = repmat('%f',1,7);
for k = 1:N
fnm = fullfile(P{k},F{k},'specimen.dat');
[fid,msg] = fopen(fnm,'rt');
assert(fid>=3,msg)
D{k} = textscan(fid,fmt,'delimiter','\t');
fclose(fid);
end
Alternatively you could try dlmread.
Categories
Find more on Standard File Formats in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!