Why does my variable iterate only once in my while loop?
3 views (last 30 days)
Show older comments
x = 1;
y = 1;
times1 = 0;
times2 = 0;
while x <= size(VideoNumber)
if number == VideoNumber(x)
times1 = times1+1;
x=x+1
else
x=x+1
end
end
Returns:
x =
2
When instead it should iterate around 4900 times
5 Comments
Sindar
on 28 Sep 2020
Edited: Sindar
on 28 Sep 2020
I'm not saying hard-code in 4934. But, if the number of iterations is known before the loop starts (here, because the size of the data isn't changed during the loop) then it makes sense to use a for loop instead of a while loop.
Also, if all you are doing is counting the number of elements equal to a certain value, any sort of loop is unnecessary:
times1 = nnz(VideoNumber == number);
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!