How can I fix "Attempted to access Y(0); index must be a positive integer or logical." MATLAB for loop error?
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to use a for loop in MATLAB and I keep getting an error message. The instructions I'm following are to create a 10000X1 vector using a random number generator and label it "e", and then a second 10000X1 vector that only contains zeros. Then using a loop I have to simulate the process Y(t)=(1-a)*Y(t-1)*e(t) where a=0.1. The code I have been attempting to run is:
Y=zeros(10000,1);
e=randn(10000,1);
for t=1,2,...,10000
a=0.1;
Y(t)=(1-a)*Y(t-1)*e(t);
end
I keep getting an error message that says: "Attempted to access Y(0); index must be a positive integer or logical." Any help is appreciated
0 个评论
回答(1 个)
Walter Roberson
2015-9-7
for t=1,2,...,10000
is not valid syntax. Please post your actual code.
Your formula has
Y(t)=(1-a)*Y(t-1)*e(t);
when t = 1, the Y(t-1) part is going to be trying to access Y(0). In MATLAB you cannot index an array at location 0.
I suspect the formula you need is
Y(t+1) = (1-a)*Y(t)*e(t);
with the "for" running from 1 to 9999. However, it is possible that instead you want the formula that you have now but with t starting from 2 in the loop.
The difference between the two formulas has to do with whether e(1) should ever be used and if so whether it should be used with Y(1) or with Y(2)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!