How do I avoid for loops when going through folders and files?

Asked by Taylor Sanchez on 11 Jul 2012

I need to reorganize some file names, based on an array of random numbers we generated. I annotated these files, and the annotations were named similarly, which my functions compare the names to overlay the annotations. Anyways my main concern is that I have been told nested for loops are bad, and that they should be avoided. I haven't ever had any good examples on how to avoid them. I figure this is 3 nested for loops, there must be some way to enhance this code. The folder/file layout is as so: https://lh6.googleusercontent.com/-7uG3uawesDk/T_2iGTofVvI/AAAAAAAAHLw/CeIO_PRz7tU/s640/MATLAB%2520%2520R2012a_2012-07-11_08-54-51.png

This is my working (but possible bugs) code: I didn't use the copyfile just yet. I was comparing the name outputs for debugging. Which seems to be working.

function [ ] = Reorganize()
%REORGANIZE Summary of this function goes here
%   Detailed explanation goes here
%plan of attack:
%load the random data array
load('randcombdata.mat');
subfolders=dir;
%Will need to go back and forth into the subfolders, etc.
 for i = 3: numel(subfolders)
    cd(subfolders(i).name);
    pictures = dir('object*.png'); %find all object*.png files.
     for j = 1: numel(pictures)
        %strip the object and .png from the filename
        pictures(j).name = strrep(pictures(j).name,'object','');
        oldfilenum = strrep(pictures(j).name,'.png','') ;
         if isnan(str2double(oldfilenum)) %it was grabbing object#_Annotated.png 
              continue;
         else
             tempoldfilenum = strcat('*',oldfilenum,'*.mat');
             oldfile = dir(tempoldfilenum);
             newfile = oldfile; %preallocating it. lazy way, Probably 
         end
         for k = 1: numel(oldfile) 
           AlphaCheck = regexprep(strrep(newfile(k).name,'object',''),'_(\w*).mat', '');
           if strcmp(AlphaCheck,oldfilenum)
               continue;
           else
               AlphaCheck = AlphaCheck(1:end-1);
           end
           if strcmp(AlphaCheck,oldfilenum) %need to run a check to make sure numbers are equal, ie 7 =7 not 27
                %Use strrep to take the oldfilenum and replace it with newfilenum
                %newfilenum is received from randcomb250
               newfile(k).name = strrep(oldfile(k).name,oldfilenum,num2str(randcomb250(str2double(regexprep(oldfilenum, '_(\w*)', '')))));
               oldfile(k).name
               newfile(k).name
           else
               continue;
           end
           end
          %newfile(1).name
       end
        %copyfile(oldfile(k).name,strcat('Randomized/',newfile(k).name));
  %forth to root.
   cd(subfolders(2).name)
   clear pictures oldfilenum temoldfilenum newfile %just to be safe and start fresh with each iteration. Unsure if necessary.
   end
  end

Any other coding tips are welcome. :)

0 Comments

Taylor Sanchez

Products

0 Answers

Contact us