read mat files with specific and dynamic name format and import data
22 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2021-7-6
编辑:Stephen23
2021-7-6
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
更多回答(1 个)
dpb
2021-7-5
编辑:dpb
2021-7-6
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 个评论
Walter Roberson
2021-7-6
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!