MATLAB: Read Images After Sorting with natsortfiles

imreadnatsortnatsortfilesnumerical order

I have a sequence of images titled "0_b.tif", "0_g.tif", "0_r.tif", "1_b.tif", … "640_b.tif", "640_g.tif", "640_r.tif". I first sorted these so that they appear in numbered order using natsortfiles. Now I am trying to make simple mean, max, min, std calculations for each b, g, and r sequence of 640 images, separately. Below is an example of just the mean calculation. I am able to generate the correct mean values, however they are still listed in the original, incorrect order before sorting.
The end product is supposed to be a 640 x 1 column vector of mean values in file numerical order.
function [X,ndx,dbg] = natsortfiles(X,rgx,varargin);
MeanNew = zeros(640,1);
for k = 1:640
D = 'C:\mypath\';
S = dir(fullfile(D,'*_b*.tif')); % selecting only the files ending with _b
N = natsortfiles({S.name});
I suspect that from here, I am accidentally bypassing the natsort function, reverting back to the original order.
F = fullfile(D,N{k});
FileNames=S(k).name;
I = imread(FileNames);
MeanNew(k,:) = mean(I , [1 2] )
end
end

Best Answer

Do NOT redefine the natsortfiles function! Do NOT save this in a file named natsortfiles!
Simply following the examples in the natsortfiles documentation and the MATLAB documentation:
D = 'C:\mypath\';
S = dir(fullfile(D,'*_b.tif'));
C = natsortfiles({S.name});
N = numel(C);
M = zeros(N,1);
for k = 1:N
F = fullfile(D,C{k});
I = imread(F);
M(k) = mean(I,[1,2]);
end