read mat files with specific and dynamic name format and import data
22 views (last 30 days)
Show older comments
matFiles = dir('s*_results.mat');
for k = 1:length(matFiles)
rawdata = fullfile(matFiles, k);
filename = importdata(rawdata);
end
myVars = {'results', 'prep'};
filedata = load(filename, myVars{:});
I'm trying to read all the files with names such as "s001_results.mat", "s002_results.mat" and so forth until "s150_results.mat" which are mat files with more than the two variables (results and prep) that I need. Essentially, I need to read the results and prep variables in all 150 of these mat files but I keep getting the error that the file cannot be imported using the importdata function. Please help!
0 Comments
Accepted Answer
Stephen23
on 6 Jul 2021
Edited: Stephen23
on 6 Jul 2021
The best approach is to use the same structure as DIR returns. This has the benefit that the filenames and filedata are automatically and correctly collated together. For example:
P = 'absolute or relative path to where the files are saved'
S = dir(fullfile(P,'s*_results.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k.name));
T = load(S); % you can optionally specify the variable names here.
S(k).prep = T.prep;
S(k).results = T.results;
end
And that is all! You can trivially access the filenames and filedata, e.g. for the second file:
S(2).name
S(2).prep
S(2).results
More Answers (1)
dpb
on 5 Jul 2021
Edited: dpb
on 6 Jul 2021
matFiles = dir('s*_results.mat');
myVars = {'results', 'prep'};
varsList=char(join(myVars));
for k = 1:length(matFiles)
load(matFiles(i).name, varsList);
end
...
The list of variables to load must be char() vector of names comma-separated or just a single name (which could include wildcards, but that doesn't work here).
See the doc for load for details on syntax.
ADDENDUM:
Your syntax results in a list, not a string and (I think) the comma delimter is requred, anyways...
>> myVars = {'results', 'prep'};
myVars{:}
ans =
'results'
ans =
'prep'
>>
whereas
>> char(join(myVars,','))
ans =
'results,prep'
>>
is the requisite char string list of variables to mimic what would type at command line interactively. I didn't test if load has been update to handle the new string class.
1 Comment
Walter Roberson
on 6 Jul 2021
No join!
matFiles = dir('s*_results.mat');
nfiles = length(matFiles);
myVars = {'results', 'prep'};
data_cell = cell(nfiles, 1);
for k = 1:length(matFiles)
data_cell{k} = load(matFiles(i).name, myVars{:});
end
data_struct = cell2mat(data_cell);
result should be a non-scalar struct array with fields results and prep
See Also
Categories
Find more on Text Data Preparation 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!