MATLAB Answers

Index exceeds the number of array elements (0).

685 views (last 30 days)
Brian Peoples
Brian Peoples on 1 Jul 2019
Edited: Guillaume on 24 Mar 2020
clc
clear all
close all
myDir = 'C:\Users\bpeoples\Downloads\SCANSNAPCODE_BDP\Numerical Comparison\Diffused Above, SV600 Raised\1st 25'; %call out folder contained in image
ext_img = '*.jpg'; %file extension of interest
a = dir([myDir ext_img]); %array of all files in folder with .jpg ext
nfile = max(size(a)) ; %file count
%read all images into a single struct
for i=1:nfile
my_img(i).img = imread([myDir a(i).name]);
end
Keep getting the error: Index exceeds the number of array elements (0).
  1 Comment
dpb
dpb on 1 Jul 2019
Have you used the debugger and checked what the file name is that you actually passed to dir()?
Hint: The solution could make use of fullfile()

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 1 Jul 2019
Edited: Guillaume on 24 Mar 2020
Yes, you will receive this error whenever your dir doesn't find any file. Three things:
  • Use meaningful variable names, dircontent is a lot better variable name than a.
  • don't build paths by string concatenation. Use fullfile instead:
dircontent = dir(fullfile(myDir, ext_img);
  • Never use max(size(vector)) to get the number of elements in a vector. When dir doesn't find any file, it returns a 0x1 vector. max of 0 and 1 is 1, even though the vector has 0 elements. Always use numel to get the number of elements. It's faster, shorter and always works.
So:
myDir = 'C:\Users\bpeoples\Downloads\SCANSNAPCODE_BDP\Numerical Comparison\Diffused Above, SV600 Raised\1st 25'; %call out folder contained in image
ext_img = '*.jpg'; %file extension of interest
dircontent = dir(fullfile(myDir, ext_img));
assert(numel(dircontent) > 0, 'No file was found. Check that the path is correct');
my_img = struct('img', cell(size(dircontent))); %preallocation of the structure
for fileidx = 1:numel(dircontent)
my_img(fileidx).img = imread(fullfile(myDir, dircontent(fileidx).name));
end
Of course, you still need to fix the initial problem which is that dir didn't find any file. Most likely, you've made a mistake with your path.
  1 Comment
dpb
dpb on 2 Jul 2019
"dir didn't find any file. Most likely, you've made a mistake with your path."
He didn't add the delimiter before catenating the filename wildcard string...so as you also note fullfile will help.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!