1
votes

I want load many files from a directory that their names have a pattern such as: data_1 & data_2 , ... , that as mentioned, the numbers in each "data_" are as the same with the counter of the main for loop.

How can I do this for matching the file names that are loading with the number of counter of the for loop. This is my imperfect code:

for i=1:100
loadpath='./folder/data/';
 load('Label_i.mat');
end
1
You can try: load(['Label_' num2str(i) '.mat']); Beside, what's the purpose of having loadpath='./folder/data/'; in each iteration if it do not change and it is not used?il_raffa
You can use sprintf with the %i format spec:load(sprintf('Label_%i.mat', i));rinkert
@il_raffa, Thank for your comment, I want load files from a specific path, but I think this solution does not solve that. Any ideas?Ben25
@rinkert, thanks, How can I read from the aforementioned directory?Ben25
If you want to add the path, you can either just load(sprintf('./folder/data/Label_%i.mat', i)); or use fullfile: load(fullfile(loadpath, sprintf('Label_%i.mat', i)));rinkert

1 Answers

3
votes

You can use fullfile and sprintf:

loadpath='./folder/data/';
for k = 1:100
    load(fullfile(loadpath, sprintf('Label_%i.mat', k)));
end