coding a conditional for loop

조회 수: 23 (최근 30일)
K Kee
K Kee 2015년 11월 2일
댓글: Walter Roberson 2019년 3월 9일
I would like to know what code I need to write a conditional for loop. More specifically, I want to check a list of values to see if they make an equation > a certain number. Then I want to continue using the values that fit the condition in the rest of my code. If they don't fit the condition then I don't want them used. Can anybody help me with this?

답변 (2개)

Walter Roberson
Walter Roberson 2015년 11월 2일
MATLAB does not have conditional for loops. MATLAB does however support code of the form
if some condition
for variable = range
some statement
end
end
and
for variable = range
if some condition
some statement
end
end
The first one checks the condition once and if it is true then runs the entire for loop to completion and otherwise does not run the for loop at all. The second one runs the for loop and for each iteration of the loop tests the condition and if the condition is true executes the statement.
If you wish to exit a for loop early then you can use "break". For example,
for variable = range
t = cos(variable);
if t < -0.88
break
end
some statement
end
This would exit the for loop the first time that cos(variable) < -0.88
  댓글 수: 2
K Kee
K Kee 2015년 11월 2일
this is very helpful. what would go in the "statement" position?
Walter Roberson
Walter Roberson 2015년 11월 2일
What would go in the "statement" position is the using the values" part of "Then I want to continue using the values that fit the condition in the rest of my code"

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


William Gaillard
William Gaillard 2019년 3월 7일
편집: William Gaillard 2019년 3월 7일
Couldn't you use a while loop to accomplish the same thing
  댓글 수: 1
Walter Roberson
Walter Roberson 2019년 3월 9일
When I re-read the question, it now looks to me as if the general form should be:
values_to_try = .... something appropriate
y = SomeFunction(values_to_try);
mask = y > a_certain_number;
selected_values = values_to_try(mask);
and then proceed to process selected_values

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by