index exceeds the number of array elements

1 回表示 (過去 30 日間)
cody madsen
cody madsen 2019 年 11 月 1 日
回答済み: Sai Bhargav Avula 2019 年 11 月 1 日
I am trying to create a vector that stores a tally and if the tally k is greater than the number of elements in the vector I want it to create a larger vector and then keep changing the elements in the vector. It seems to be working for integers 1-3 but it errors out when I try to input 4. Why would this be?
function OrderCount = proj1(m)
OrderCount = zeros(1,1)
T = zeros(1,4)
for x1 = 0:m
for x2 = 0:m
for x3 = 0:m
for x4 = 0:m
T(1) = x1;
T(2) = x2;
T(3) = x3;
T(4) = x4;
k = 0;
while T(1) > 0 || T(2) > 0 || T(3) > 0 || T(4) > 0
NewT = T(1);
T(1) = abs(T(1)-T(2));
T(2) = abs(T(2)-T(3));
T(3) = abs(T(3)-T(4));
T(4) = abs(T(4)-NewT);
k = k + 1;
end
if k > length(OrderCount)
OrderCount(k+1) = 1;
else
OrderCount(k+1) = OrderCount(k+1)+1;
end
end
end
end
end
  1 件のコメント
cody madsen
cody madsen 2019 年 11 月 1 日
It also is creating a larger vector just fine for integers 1,2,3 but not 4

サインインしてコメントする。

回答 (1 件)

Sai Bhargav Avula
Sai Bhargav Avula 2019 年 11 月 1 日
Hi,
Try changing the below mentioned part of the code to this.
if k > length(OrderCount)
OrderCount(k+1) = 1;
else
OrderCount(k+1) = OrderCount(k+1)+1;
end
The issue is when K = length of the OrderCount you are trying to access the next element of the array.
Hope this helps!

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by