Index exceeds the number of array elements (0).

386 views (last 30 days)
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.
  2 Comments
Ammar Adnan
Ammar Adnan on 2 Apr 2022
% In this program, we want to find the centre and aim point of each element
% on the coil surface
clc;
clear;
tic
data=xlsread('focus.csv');
index =find(isnan(data(:,1))==1);
l=length(data);
nodes =data(1:index(1)-1,2:4);
faces =data(index(2)+1:l,1:4) +1;
% Finding the indices of triangular (it) and quadrilateral (iq) elements
it=find(isnan(faces(:,4))==1); t=length(it);
iq=find(isnan(faces(:,4))==0); q=length(iq);
Index exceeds the number of array elements (0).
Error in stinput_focus (line 9)
nodes =data(1:index(1)-1,2:4);
what's the error ?

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!