Why does my variable iterate only once in my while loop?

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 件のコメント

Sindar
Sindar 2020 年 9 月 28 日
size(VideoNumber)
is a vector, so you shouldn't directly compare it to x
also, why are you using a while loop when you seem to know exactly how many iterations to do?
Ikenna Nebolisa
Ikenna Nebolisa 2020 年 9 月 28 日
Despite me knowing that it should iterate exactly 4934 times, my code needs to be general enough to work for any number sized data, so I'm trying to compare x to its size rather than a specific number.
per isakson
per isakson 2020 年 9 月 28 日
What's the value of VideoNumber ?
Maybe you want to replace size(VideoNumber) by length(VideoNumber)
Sindar
Sindar 2020 年 9 月 28 日
編集済み: Sindar 2020 年 9 月 28 日
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);
Ikenna Nebolisa
Ikenna Nebolisa 2020 年 9 月 28 日
Thank you all for your comments. I was able to get it to work.

サインインしてコメントする。

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2020 年 9 月 27 日

コメント済み:

2020 年 9 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by