필터 지우기
필터 지우기

How to use a for cycle for opening .mat files

조회 수: 4 (최근 30일)
Hugo
Hugo 2022년 2월 8일
답변: Image Analyst 2022년 2월 9일
Hi,
In the directory c:\MAT (it's not my workspace directory), I have the following .mat files:
A1B1.mat
A1B2.mat
A1B3.mat
A2B1.mat
A2B2.mat
A2B3.mat
A3B1.mat
A3B2.mat
A3B3.mat
How can I automate the opening/import of them, for example, using a for cycle, saving each .mat file in a new variable?
Best regards,

채택된 답변

Stephen23
Stephen23 2022년 2월 8일
편집: Stephen23 2022년 2월 8일
The general concept is shown here:
You can easily store the imported data in the same structure as DIR returns, e.g.:
P = 'C:\MAT';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = load(F);
end
All of the imported file data will be stored in the structure S. For example, for the second file:
S(2).name % filename
S(2).data % structure of the imported data
If each file contains exactly one variable of the same name then you can simplify the later processing by specifying that variable when importing:
P = 'C:\MAT';
S = dir(fullfile(P,'*.mat'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
T = load(F);
S(k).data = T.nameOfTheVariable;
end
Note that after then loop you can use this syntax, which might make processing your data easier:
  댓글 수: 2
Hugo
Hugo 2022년 2월 9일
Thank you for your useful answer. your solution works.
Now, if I would like to load each .mat file that your code originates into a variable,, how shall my "load" command be?
Stephen23
Stephen23 2022년 2월 9일
"Now, if I would like to load each .mat file that your code originates into a variable"
They are already in a variable, the structure S. You can access them simply and efficiently using indexing.
If you want each file loaded into a separate, dynamically named variable, you might like to read this:

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

추가 답변 (1개)

Image Analyst
Image Analyst 2022년 2월 9일

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by