1

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
5
  • 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? Commented May 15, 2020 at 16:04
  • You can use sprintf with the %i format spec:load(sprintf('Label_%i.mat', i)); Commented May 15, 2020 at 16:05
  • @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? Commented May 15, 2020 at 16:07
  • @rinkert, thanks, How can I read from the aforementioned directory? Commented May 15, 2020 at 16:08
  • 1
    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))); Commented May 15, 2020 at 16:09

1 Answer 1

3

You can use fullfile and sprintf:

loadpath='./folder/data/';
for k = 1:100
    load(fullfile(loadpath, sprintf('Label_%i.mat', k)));
end
Sign up to request clarification or add additional context in comments.

2 Comments

In the case, when the saved data in the disk, starts for example from data_125, data_126 , ..., with considering that the counter of the main loop starts from 1 to N, How the code can be adapted for this aim?
Could you clarify your folder/file name structure (perhaps in the question body)? I don't understand what you are trying to do now. Just add the update at the bottom with sufficient details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.