Looping if between 2 numbers

41 ビュー (過去 30 日間)
jason
jason 2022 年 9 月 21 日
編集済み: Jeffrey Clark 2022 年 9 月 21 日
I am trying to create a for loop that will only loop if x is between two number like 0<=x & x>= 12, but when I use the & symbol it does not work.

回答 (2 件)

Jeffrey Clark
Jeffrey Clark 2022 年 9 月 21 日
@jason, the and operator (&) produces a logical (true/false 1/0) result - not a range of values. Please look at MATLAB documentation and specifically Find logical AND - MATLAB and & (mathworks.com) and for loop to repeat specified number of times - MATLAB for (mathworks.com)
  1 件のコメント
Jeffrey Clark
Jeffrey Clark 2022 年 9 月 21 日
編集済み: Jeffrey Clark 2022 年 9 月 21 日
@jason, perhaps you are saying loop between values but intend to while loop for your indicated range of x (especially if x is a non integer value) example:
x = someScalar; % not an array
while 0<=x & x<=12 % you really want to continue when less or equal to 12 not x>=12
% do something to change x
if wantToBreakOutEarly
break
end
end
% will reach this point if ~(0<=x & x<=12) | wantToBreakOutEarly

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


John D'Errico
John D'Errico 2022 年 9 月 21 日
編集済み: John D'Errico 2022 年 9 月 21 日
As @Jeffrey Clark said, the & operator is a LOGICAL operator. Perhaps what you want to do is have a loop over a discontigous domain? For example, you can do this:
S = [-5:0, 12:15];
for s = S
disp(s)
end
-5 -4 -3 -2 -1 0 12 13 14 15
Is that what you were looking to do?
No, as I re-read your question, I think it is not.
You asked about a loop that ONLY operates when X is in some interval. And that surely means a while loop. So you can do this:
x = randi(18) - 3;
while (x >= 0) && (x <= 12)
disp(x)
x = randi(18) - 3;
end
1 6 4 12 8 3 8 10 0 12 9 11 7 8 7 10
disp("final value of x that failed: " + x)
final value of x that failed: 15
So as long as x remains in the interval of interest, the loop continues. Is that what you want?

カテゴリ

Find more on Loops and Conditional Statements in Help Center and File Exchange

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by