필터 지우기
필터 지우기

How do I avoid the error message "Index exceeds the number of array elements" in a for loop?

조회 수: 4 (최근 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

채택된 답변

Jan
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

추가 답변 (1개)

Syed Ahson Ali Shah
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
j = 1
j = 2
j = 3
j = 4
j = 5
j = 6
j = 7
j = 8
j = 9
j = 10
j = 11
j = 12
j = 13
You might do like this:
day=[1,6,13];
for j = day
j
% clearly j takes the values you wanted
end
j = 1
j = 6
j = 13

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by