フィルターのクリア

Changing the step in a for loop

255 ビュー (過去 30 日間)
Alexandru Miculescu
Alexandru Miculescu 2015 年 3 月 8 日
コメント済み: Guillaume 2015 年 3 月 8 日
Hi! Easy question for you guys! How can i get the same output in matlab? Here's the code in c++ where the output is 0, 2, 4, 6, 8, whereas in matlab is 1 to 10. Thanks!
if true
for (int i = 0; i < 10; i++)
{
cout << i << " ";
i = i + 1;
}
for i=0:9
i = i+1
end
}

回答 (3 件)

Stephen23
Stephen23 2015 年 3 月 8 日
編集済み: Stephen23 2015 年 3 月 8 日
for k = 0:2:8
... some code here
end
Or even better would be to forget about those low-level loops like you need in C, and learn to vectorize your code. The documentation states:
Vectorizing your code is worthwhile for several reasons:
  • Appearance: Vectorized mathematical code appears more like the mathematical expressions found in textbooks, making the code easier to understand.
  • Less Error Prone: Without loops, vectorized code is often shorter. Fewer lines of code mean fewer opportunities to introduce programming errors.
  • Performance: Vectorized code often runs much faster than the corresponding code containing loops.
Forget about low-level languages, and learn to utilize MATLAB's programming concepts.

Alexandru Miculescu
Alexandru Miculescu 2015 年 3 月 8 日
編集済み: Alexandru Miculescu 2015 年 3 月 8 日
Thank you for your answer, i'll check that link.
for i=1:nr_games
if ( 1+fix(6*rand) ) == 6
i=i+1; % here i want to increment the i
if ( 1+fix(6*rand) ) == 6
luck = luck + 1;
end
end
What i realy want to do is to increment manually the step when ( 1+fix(6*rand) ) == 6, because i generated myself another random number.

Jos (10584)
Jos (10584) 2015 年 3 月 8 日
For-loops in matlab behave a little different than for loops in C. You might be in need of a While-loop.
for k=1:5
disp(k)
k = 100 ;
end
for k = [10 3 5 6]
disp(k) ;
end
k = 1 ;
while k < 5
k = k + 2 ;
disp(k)
end
  1 件のコメント
Guillaume
Guillaume 2015 年 3 月 8 日
To follow up on Jos' answer, you need to understand that for just iterates over the columns of the vector/matrix that you give it. In C++ terms, it behaves like std::for_each on a const sequence.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by