Info
此问题已关闭。 请重新打开它进行编辑或回答。
How to remedy the error for accessing an Index, but the index is out of bounds?
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!