How can I cd to to different directories with a changing name in a for loop

3 views (last 30 days)
As title
If I have the following directories, and I want to read data under these paths
./data_1/temp.txt
./data_2/temp.txt
./data_3/temp.txt
for i=1:3
cd ./data_$i
j(i)=dlmread('temp.txt');
cd ..
end
How can I make it happens?
Thank you

Accepted Answer

Image Analyst
Image Analyst on 9 Oct 2011
newFolder = sprintf('./data_%d', i);
cd(newFolder);
However, in my opinion, you're better off just constructing the full file name with fileparts() and fullfile() than changing the directory. I'd leave the directory alone and just read in the file giving dlmread the full filename (folder + base filename + extension).
fullFileName = sprintf('./data_%d/temp.txt',i);
j{i} = dlmread(fullFileName);

More Answers (0)

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!