Keep getting "Index exceeds number of array elements (1)" message
Show older comments
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 Comments
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.
Reem Gawish
on 21 Apr 2020
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!