Importing .mat files in a loop

조회 수: 9 (최근 30일)
ilan ancelseritcioglu
ilan ancelseritcioglu 2023년 2월 15일
댓글: ilan ancelseritcioglu 2023년 2월 15일
Hello everyone, I have 20 .mat files in the same folder and named like following:
data_1, data_2, data_3, ...data_20
and each has 2 tables and 2 variables inside
is there an easy way to import/load these files in a loop or with a command?
Thanks in advance

채택된 답변

CAM
CAM 2023년 2월 15일
for z=1:20
filename = ['data_', num2str(z)];
s(z) = load(filename); % Load variables into a structure
end

추가 답변 (1개)

Luca Ferro
Luca Ferro 2023년 2월 15일
편집: Luca Ferro 2023년 2월 15일
let's say you are in the directory, then:
matFiles=dir ('*.mat'); %finds all the .mat files (struct)
[NoF,~]=size(matFiles);
for ii=1:NoF %loops through them
matFileName=matFiles(ii).name; %get their name (string)
load(matFileName(1:end-4); %load them, cutting the '.mat' extention from the string
end
probably there is some better or faster method but this should work.
This also works for any generic .mat file regardless of the name as long as you are in the same directory.

카테고리

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