Keep getting "Index exceeds number of array elements (1)" message
1 次查看(过去 30 天)
显示 更早的评论
Hi, I have this code below, which works when I simplify the code to simply add to either x or y arrays, but doesn't work when I'm doing both, can anyone help me figure out why this may be? I'm being told from the error message that there's something wrong with "x(t)=x(t-1)-1;"
x(1)=0;
y(1)=0;
c=clock;
z=c(1,6)*1000;
rand('seed',z);
for i=1:50
r(i)=floor((3-1)*rand(1)+1);
r2(i)=floor((5-1)*rand(1)+1);
end
for t=2:50
if r(t)==1
if mod(r2(t),2)==0
x(t)=x(t-1)+1;
else
x(t)=x(t-1)-1;
end
end
if r(t)==2
if mod(r2(t),2)==0
y(t)=y(t-1)+1;
else
y(t)=y(t-1)-1;
end
end
end
disp(x)
disp(y)
2 个评论
Toey
2020-4-21
编辑:Toey
2020-4-21
Hi Reem,
In your code, x & y only increase their sizes when r(t)==1 and r(t)==2, but your index t increases by 1 every loop. This is when there's mismatch between indexing and the size of x,y.
To fix the issue, you can preallocate x,y in the beginning of your code
x=zeros(50,1); y=zeros(50,1);
or having x(t) =0 in the else statement when r(t)==1 isn't met.
采纳的回答
Sriram Tadavarty
2020-4-21
Hi Reem,
Make minor modification to the code to avoid that error as shown below:
x(1)=0;
y(1)=0;
c=clock;
z=c(1,6)*1000;
rand('seed',z);
for i=1:50
r(i)=floor((3-1)*rand(1)+1);
r2(i)=floor((5-1)*rand(1)+1);
end
for t=2:50
if r(t)==1
if mod(r2(t),2)==0
x(t)=x(t-1)+1;
else
x(t)=x(t-1)-1;
end
else
x(t) = 0; % Added this to ensure that value is stored as zero, when r(t) is not equal to 1
end
if r(t)==2
if mod(r2(t),2)==0
y(t)=y(t-1)+1;
else
y(t)=y(t-1)-1;
end
else
y(t)=0; % Added this to ensure that value is stored as zero, when r(t) is not equal to 2
end
end
disp(x)
disp(y)
Hope this helps.
Regards,
Sriram
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!