How to position flexibly the start of a for cycle?
이전 댓글 표시
My code is something like this:
expressions_1
expressions_2
expressions_3
I need a for cycle, but the start of the cycle depends on a parameter. So I would like that my code behave like this in case of param = 1:
for i=1:N
expressions_1
expressions_2
expressions_3
end
but for param = 2 it should be:
expressions_1
for i=1:N
expressions_2
expressions_3
end
How to do this in general?
채택된 답변
추가 답변 (1개)
dpb
2015년 6월 16일
There is no absolutely general answer to such a question; only a specific solution to the specific condition. In this case it's fairly simple to write
for i=1:N
if param==2 & i==1
expressions_1
end
expressions_2
expressions_3
end
Alternative constructions are, of course, possible, but you'll have to consider any future modifications wanted/needed as they come up.
댓글 수: 3
Mr M.
2015년 6월 16일
"Is it ... possible ... to start a for cycle inside an if statement but end it outside?"
Nope; each construct has to be complete within any other.
As noted, there is no general solution for any possible set of conditional logic; you have to write the logic that fits the situation you have.
Sometimes writing things as state variables and as transition via a "state machine" is a viable alternative.
ADDENDUM
I'll qualify the above just a little...as I think you intended the question the answer is as given, "no"; in that there is no way that clauses aren't matched and completely nested within any higher level construct.
But, you can manage to break out of a for loop and also break an if pattern but it requires having a break condition coded inside the for and more than likely some additional logical "flag" variables to use to control the location of where in a SWITCH or nested IF the execution were to branch. In languages w/ GOTO there's a little more flexibility in going from point A to point B but it comes at a price in code legibility and it's possible to write any algorithm without it. TMW has chosen the "structured" route entirely to protect users from themselves of writing "spaghetti code" by not incorporating the statement at all.
ADDENDUM 2
Even with GOTO there are limits on not being able to jump from outside into a DO...ENDDO (Fortran syntax) and the like. In early versions of FORTRAN there were some rather unique things regarding "EXTENDED DO" that were allowed, but that turned out to be so problematic the feature was removed from the language Standard going forward from F90. Even it would NOT let you do what you're proposing above, however.
카테고리
도움말 센터 및 File Exchange에서 Assumptions에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!