Search code examples
matlabfilerandommovetraining-data

randomly move files from a folder to another folder?


I am trying to move my files and create a new folder to put those files there. I have many .png files in my images folder in my MATLAB directory. I want to randomly choose 80% of them and move them to another folder called training folder in my matlab directory. Heres my code which is not working. it cant find the file to move :(

data_add = fullfile(cd,'images');
all_files = dir(data_add);
all_files = all_files(3:end);
num_files = numel(all_files);
image_order = randperm(num_files);
for k = 1:(image_order)*0.8  
     file_name = all_files(k).name;
     file_add = all_files(k).folder;
     file_to_move = fullfile('path_to_images\images',file_name);
     mkdir training
    movefile file_to_move training

end

Solution

  • A couple issues here:

    1. Like Flynn comments, the call to mkdir training only needs to be made once, so you can place it before your loop.
    2. You may be thinking about the variable image_order incorrectly when it comes to your for loop.

      The call image_order = randperm(num_files); produces an array of randomly ordered indices from 1:num_files, which is helpful. However, the expression (image_order)*0.8 is actually multiplying each of these indices times 0.8, such that they are no longer valid, integer indices (aside from a few, like 8 which would become 1).

      I think what you are attempting and wanting to do is this:

      mkdir('training');  
      for k = 1:num_files*0.8
         randK = image_order(k);
         file_name = all_files(randK).name;
         file_to_move = fullfile(data_add,file_name);
      
         movefile(file_to_move, 'training'); % using function style
       end
      

    You may run into other issues next depending on where the folder training is located and where you are running your script from, but this should be closer to what you are to get, and at least locate the files for you.