Counter not working in for loop

I have a counter in a for loop like this:
x = 0;
for i = 1:10
x = x+1;
% code that uses the counter
end
However, when I was debugging and removed the semicolon from the x = x+1 statement I get:
x =
0×1 empty double column vector
When I debugged and used disp(i) and disp(x), it would only display the value of i and not x. Does anyone know how to fix this?

3 个评论

Do you have a clear workspace? I dont see anything wrong with that statment and it works fine on my machine.
it also seems like x is just equivalent to i in every iteration, have you considered just using i?
the for loop is actually a nested for loop and x is a counter for every iteration of both for loops

请先登录,再进行评论。

回答(1 个)

Star Strider
Star Strider 2019-2-13

0 个投票

We cannot see the ‘code that uses the counter’. Check to see if your code is somehow clearing ‘x’ or setting ‘x’ to [].

4 个评论

A simplistic version of the code is:
array(x, 1) = i;
x = x+1;
array(x, 1) = i+1;
x = x+1;
%and so on
So it shouldn't be clearing x or setting it to [].
Also, it works when I type the code in the command window but just not when I run it as the function it is in.
‘So it shouldn't be clearing x or setting it to [].’
It is obvious that something is clearing it. I suggest that you use the debugging tools to see what ‘x’ is doing, and where.
do you have any suggestions for debugging tools other than the ones I've mentioned using?

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by