How do I avoid the error message "Index exceeds the number of array elements" in a for loop?
1 次查看(过去 30 天)
显示 更早的评论
Hello,
I know that maybe the solution might be easier than expected but I am blocked at the moment.
I want to extract all my .csv files from an especific folder. I am able to do what is meant but at the end of the for loop I recieve the error message
"Index exceeds the number of array elements"
I know there should be something related to the indexes on the loop, but I have tried some modifications and I am not able to fix it.
The basic main idea is to extract an especific group of files called Gala which has two variables for the loop.
The first variation is the day, "d',num2str(day(j),'%i')", e.g. d1,d2,etc.. and the second some samples num2str(ii,'%i'), e.g. 1, 2, etc..
After the file is called I store it into a cell called dataBase
I need to do more code after these little lines, therefore it is important for me to solve this
Thanks in advance for your advices. The code is below
day=[1,6,13];
for j = day(1):day(3)
for ii = 1:2
fn = strcat('C:\Users\Documents\Grafics\Apples\Gala d',num2str(day(j),'%i'),{' '},num2str(ii,'%i'),'.csv')
fn=char(fn)
Gala= readtable (fn);
dataBase_Gala{j,ii}=Gala;
end
end
0 个评论
采纳的回答
Jan
2022-2-15
编辑:Jan
2022-2-15
day(1):day(3) is the vector 1:13.
Some other simplifications, which uses a counter to access the days:
folder = 'C:\Users\Documents\Grafics\Apples\';
dayList = [1, 6, 13];
for j = 1:numel(dayList)
day = dayList(j);
for ii = 1:2
filename = sprintf('Gala d%i %i.csv', day, ii);
file = fullfile(folder, filename);
dataBase_Gala{j, ii} = readtable(file);
end
end
0 个评论
更多回答(1 个)
Syed Ahson Ali Shah
2022-2-15
the variable in j takes on 13 values.
day=[1,6,13];
for j = day(1):day(3)
j
end
You might do like this:
day=[1,6,13];
for j = day
j
% clearly j takes the values you wanted
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!