Info

This question is closed. Reopen it to edit or answer.

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

1 view (last 30 days)
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

Answers (1)

Adam
Adam on 5 Dec 2016
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!