How do I load multiple .mat files and save them as variables?

조회 수: 45 (최근 30일)
Paul
Paul 2022년 9월 2일
편집: Stephen23 2022년 9월 2일
So I'm trying to load multiple .mat files into matlab. In the current folder, my .mat files are named "test1.mat" to "test2036.mat", so 36 test cases in total.
Can I have some help in importing all of the test cases and saving as variables such as "test1Data", "test2Data" etc.
Anyhelp is much appreciated! Thanks :)
  댓글 수: 2
Stephen23
Stephen23 2022년 9월 2일
편집: Stephen23 2022년 9월 2일
"...and saving as variables such as "test1Data", "test2Data" etc."
Best avoided:
"...my .mat files are named "test1.mat" to "test2036.mat", so 36 test cases in total."
From 1 to 2036 gives ... 2036 test cases. Or can multiple files correspond to one test case?
Paul
Paul 2022년 9월 2일
Thanks for your quick response, I made an error in the original question, it shouldn't read test2036.mat but just test36.mat

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2022년 9월 2일
편집: Stephen23 2022년 9월 2일
P = '.'; % absolute or relative path to where the files are saved.
S = dir(fullfile(P,'test*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
C = struct2cell(load(F));
S(k).data = C{1}; % assuming exactly one variable per file, which
end % is important information you did not tell us.
Your file data will be stored in the structure array S. You can trivially loop over all of S to process the imported data.
For example the second file name and its corresponding data:
S(2).name
S(2).data
You can also use the following convenience syntax to access the field data of S:
If you expect those files to be listed in alphanumeric order, you can download and use this:

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by