index exceeds the number of array elements

1 次查看(过去 30 天)
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 个)

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 CenterFile Exchange 中查找有关 Loops 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