Reputation: 169
I have a folder named "Photos" that is a subfolder of the current directory. Inside that folder, there are four subfolders with names "Order1", "Order2", "Order3", "Order4". I am trying to open these subfolders using a loop.
The following code is not working.
for i=1:4
current_path=pwd;
cd(current_path');
cd('Photos\Order%d',i);
end
Upvotes: 0
Views: 83
Reputation: 65470
There are a lot issues going on here at the same time.
The primary issue is that you are changing directories each time through the loop but you're also getting the value of the current directory (pwd
) each time. The directory doesn't automatically reset to where you were when it goes back to the top of the loop. I think you expect current_path
to be the folder you started in and be the same for all iterations.
You need to use sprintf
or something similar to create your "OrderN" folder names. cd
doesn't know what to do with the format specifier you're trying to use.
You should always use fullfile
when concatenating file paths. Period.
You should use absolute paths when possible to remove the dependence upon the current directory.
Do you really need to change the working directory? If you're trying to load files within these folders, please consider using absolute file paths to the files themselves rather than changing folders.
If you are going to do this this way, please be sure to reset the path back to where it was at the end of the loop. There is nothing worse than running code and ending up in a directory that is different than where you were when you called it.
To actually make your code work, we could do something like this. But given all of my points above (specifically, 4-5), I would strongly consider a different approach.
startpath = pwd;
for k = 1:4
folder = fullfile(startpath, 'Photos', sprintf('Order%d', k));
cd(folder)
end
% Set the current directory to what it was before we started
cd(startpath)
Upvotes: 2