index exceeds the number of array elements

1 view (last 30 days)
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 Comment
cody madsen
cody madsen on 1 Nov 2019
It also is creating a larger vector just fine for integers 1,2,3 but not 4

Sign in to comment.

Answers (1)

Sai Bhargav Avula
Sai Bhargav Avula on 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!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!