index exceeds the number of array elements

1 vue (au cours des 30 derniers jours)
cody madsen
cody madsen le 1 Nov 2019
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 commentaire
cody madsen
cody madsen le 1 Nov 2019
It also is creating a larger vector just fine for integers 1,2,3 but not 4

Connectez-vous pour commenter.

Réponses (1)

Sai Bhargav Avula
Sai Bhargav Avula le 1 Nov 2019
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!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by