Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to remedy the error for accessing an Index, but the index is out of bounds?

조회 수: 1 (최근 30일)
gary_feesher
gary_feesher 2016년 12월 5일
마감: MATLAB Answer Bot 2021년 8월 20일
Hi,
I am receiving the following error when I run the loop below. Any ideas on how to remedy this error?
Attempted to access stocks.Open(17); index out of bounds because numel(stocks.Open)=16.
Error in mopso (line 22)
stocks(i).ror(j) = (stocks(i).Open(j+1) - stocks(i).Open(j))/stocks(i).Open(j);
My for loop:
for i=1:length(stocks)
stocks(i).ror = zeros(num_period, 1); % Rate of return of stocks i
% Calculate all rate of return of stock i
for j=1:num_period
% Rate of returns
stocks(i).ror(j) = (stocks(i).Open(j+1) - stocks(i).Open(j))/stocks(i).Open(j);
end
rors(:,i) = stocks(i).ror;
end

답변 (1개)

Adam
Adam 2016년 12월 5일
You created your object to have size num_period, then you loop around from j = 1:num_period, but you use j+1 to index into your structure so when j reaches num_period this will go out of bounds.
I don't know enough about what your code is doing to know how to fix it correctly, but to avoid the error don't try to access the +1 element when looping up to the maximum size of the array.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by