read mat files with specific and dynamic name format and import data
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!
Accepted Answer
More Answers (1)
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
Categories
Find more on Large Files and Big Data 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!