While Loop, with a user made function

3 ビュー (過去 30 日間)
James Wilson
James Wilson 2021 年 4 月 22 日
コメント済み: David Hill 2021 年 4 月 22 日
I am trying to create a while loop that compares the output of a function that is perviously in the script code to a loaded martix. I am trying to use a variable to account for the amount generators producing the power. Both usage matrix and the T_Energy martix are the same size.
Gen = 1;
T_Energy = Gen*Energy_Out;
while T_Energy < usage
T_Energy = Gen*Energy_Out;
Gen = Gen + 1;
end
Once the code is ran, the Gen value still stays at 1, and it doesn't look like the martices are compared.

採用された回答

Steven Lord
Steven Lord 2021 年 4 月 22 日
From the documentation for the while keyword: "while expression, statements, end evaluates an expression, and repeats the execution of a group of statements in a loop while the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
So if your condition is nonempty and nonscalar, for the body of the while statement to execute all the elements of the condition must be true.
while [1 2] < 1.5
disp("Yes!")
end
Nothing gets displayed by that code. While 1 is less than 1.5, 2 is not. If you want the condition to be considered satisfied if any of the elements of the condition are true:
iter = 0;
while any([1 2] < 1.5) & iter < 5
disp("Yes!")
iter = iter + 1;
end
Yes! Yes! Yes! Yes! Yes!
I added the iter variable so this wasn't an infinite loop.

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 4 月 22 日
while TEST
is the same as
while all(reshape(TEST, [], 1))
In other words it is considered false if there is even one entry in TEST that is 0.
Your condition is true for some elements of it but false for other elements of it, and while stops at the first false.

David Hill
David Hill 2021 年 4 月 22 日
You will need to figure out how you want to compare the maxtrices, less than (<) compares element-to-element producing a logical matrix the same size. When you apply the if statement, it only looks at the first element of the logical matrix. You could sum all elements and compare, but I don't know what you want.
if sum(T_Energy,'all')<sum(usage,'all')
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 4 月 22 日
When you apply the if statement, it only looks at the first element of the logical matrix.
Not true!
itercount = 0;
while [true, false]
disp('got here')
itercount = 0
break
end
disp(itercount)
0
If it only looked at the first element, then it would have done the body.
David Hill
David Hill 2021 年 4 月 22 日
Thanks, I should have tested that hypotheses.

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

カテゴリ

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