1. Read all file names inside a range of folders
The following code will look into folders, with regarding to the folder name pattern, and read all file names inside the dedicated folder.Example: Data files are collected from many user, and each user has it own folder with the name u001, u002,...These user folders belong to a root folder (as in the following photo).
The MATLAB code to read all data file names in this case is:
fileCfg=struct(...
'rootFolder','D:\Experiment\BodyDyn',...
'userFolderPattern','^u\d+$',... %regular expression for user folder names
'extension','set'); %File extension filter
userf = dir(fileCfg.rootFolder);
userf = regexpi({userf.name},fileCfg.userFolderPattern,'match');
userf = [userf{:}];
%userf is now a row matrix that holds all user folder names
dataFiles=[];
for i=1:size(userf,2)
temp=char(strcat(fileCfg.rootFolder,'\',userf(i),'\*.',fileCfg.extension)); %full path to data folder
temp2 = (dir(temp)); %this will cause error if the file date is empty
temp2 = { temp2.name };
dataFiles=[dataFiles; temp2'];
%dataFiles is now a vector that holds all file names
end
Important functions that you may need to understand: dir (list folder contents), regexpi (match regular expression with case insensitive).
'rootFolder','D:\Experiment\BodyDyn',...
'userFolderPattern','^u\d+$',... %regular expression for user folder names
'extension','set'); %File extension filter
userf = dir(fileCfg.rootFolder);
userf = regexpi({userf.name},fileCfg.userFolderPattern,'match');
userf = [userf{:}];
%userf is now a row matrix that holds all user folder names
dataFiles=[];
for i=1:size(userf,2)
temp=char(strcat(fileCfg.rootFolder,'\',userf(i),'\*.',fileCfg.extension)); %full path to data folder
temp2 = (dir(temp)); %this will cause error if the file date is empty
temp2 = { temp2.name };
dataFiles=[dataFiles; temp2'];
%dataFiles is now a vector that holds all file names
end
2. Save results to file
In the following code, it will generate the file that packs the variables varX and varY. This file will be saved in the same folder of the current M file.fileFullPath=mfilename('fullpath');
temp=strsplit(fileFullPath,'\'); %decompose the fullpath into folder parts and file name part
temp(end)=[]; %remove file name part
temp=strjoin(temp,'\'); %temp is now the path to the folder of current M file
filepath=strcat(temp, '\', datestr(now,'yyyymmdd_HHMM'), '_myData.mat');
save(char(filepath),'varX', 'varY'); %save file with timestamp
disp(['File is saved to: ' filepath]);
(Nguyen My - 2015/04/20)