필터 지우기
필터 지우기

read mat files with specific and dynamic name format and import data

조회 수: 21 (최근 30일)
Sam N
Sam N 2021년 7월 5일
댓글: Sam N 2021년 7월 6일
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!

채택된 답변

Stephen23
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
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
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 CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by