F = {S(X(1:5)).name}; % randomly select 5 filenames.
That gives you 5 filenames relative to the current folder
fn = fullfile(P,D,F{ii});
That tries to index one of the five filenames according to the folder index. So if you had reached the 10th folder, you would be trying to access the 10th filename out of 5.
You are looping on jj at that point, so you should be using F{jj} not F{ii}
Best Answer