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

조회 수: 1 (최근 30일)
Reem Gawish
Reem Gawish 2020년 4월 21일
댓글: Reem Gawish 2020년 4월 21일
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
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.
Reem Gawish
Reem Gawish 2020년 4월 21일
Just tried this and got it working! Thanks so much!

댓글을 달려면 로그인하십시오.

채택된 답변

Sriram Tadavarty
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
  댓글 수: 1
Reem Gawish
Reem Gawish 2020년 4월 21일
Thanks so much for your help! Finally understood what the problem was lol

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by