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

3 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by