Keep getting "Index exceeds number of array elements (1)" message

1 view (last 30 days)
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
Toey
Toey on 21 Apr 2020
Edited: Toey on 21 Apr 2020
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.

Sign in to comment.

Accepted Answer

Sriram Tadavarty
Sriram Tadavarty on 21 Apr 2020
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

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!