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