Hi,
I am looking for a tricky command which I can use it inside a 'for' loop which will enables me to allow the loop works in every 10th step.
For example:
k=0
for i=1:30
(command)
k=k+1
end
So at the end of the 'for' loop I want k=3.
Any idea?? Many thanks!!

 채택된 답변

Chad Greene
Chad Greene 2015년 2월 8일

0 개 추천

A few things:
First, try to avoid using i as a variable, because by default in Matlab i = sqrt(-1). I'm going to switch your i to n.
As you've set up your loop, k and i will always be the same. Why not just use,
for n = 1:10:30
(commands)
end
If you need to run the loop for n = 1:30 (the same thing as n = 1:1:30), but you want to do some special commands when n = 1, 11, and 21, consider using mod.
for n = 1:10:30
(commands)
if mod(n,10)==1
(do something fancy)
end
end

댓글 수: 4

Panty
Panty 2015년 2월 8일
Thank you Chad. It looks fine.
Panty
Panty 2015년 2월 8일
Chad, using exactly your 2nd example, if I want to do some special commands when n=10,20,30 how can i write the mod command??
Thanks
Stephen23
Stephen23 2015년 2월 8일
mod(n,10)==0
Chad Greene
Chad Greene 2015년 2월 8일
...What Stephen said.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 2월 8일

댓글:

2015년 2월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by