MATLAB: Issues with sort_nat and natsortfiles; error improper matrix reference

sort

hello, im using the following code :
folderName = 'C:\Users\Shruthi\Desktop\project\A data\SegmentedCharacters';
Imgs = dir(fullfile(folderName, '*.jpg'));
C={Imgs.name};
cx=natsortfiles(C)
q=1;
for blah blah
Img = imread(fullfile(folderName, cx(q).name)); % Read image

q=q+1;
blah blah
end
but it gives me this error
Improper index matrix reference.
Error in Untitled5 (line 142)
Img = imread(fullfile(folderName, cx(q).name)); % Read image
could anyone tell me how i can rectify this? Thank you!

Best Answer

natsortfiles returns a cell array, not a structure. Just like sort it returns the same cell array that was provided to it, just sorted into a particular order. Do you expect sort to return a structure when you pass it a cell array? As I wrote in the help quite clearly, natsortfiles has output " Y = Cell of Strings, X with all strings sorted into natural-order."
Not only did I state that the output is a cell array I also gave several examples in the FEX description, in the M-file help, and also in the HTML documentation, such as this simple example:
D = 'natsortfiles_test'; % directory path
S = dir(fullfile(D,'*.txt')); % get list of files in directory
N = natsortfiles({S.name}); % sort file names into order
for k = 1:numel(N)
fullfile(D,N{k})
end
Notice that in all of those examples the output is a cell array (just like the input is). But you are trying to access the output as if it was a structure with fields:
cx(q).name
...but a cell array does not have fields! So once you stop trying to access the cell array as if it was a structure, and start to access the cell array using cell array indexing (just like the examples I wrote show) then that error will disappear.