index exceeds the number of array elements

1 visualización (últimos 30 días)
cody madsen
cody madsen el 1 de Nov. de 2019
Respondida: Sai Bhargav Avula el 1 de Nov. de 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 comentario
cody madsen
cody madsen el 1 de Nov. de 2019
It also is creating a larger vector just fine for integers 1,2,3 but not 4

Iniciar sesión para comentar.

Respuestas (1)

Sai Bhargav Avula
Sai Bhargav Avula el 1 de Nov. de 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!

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by