Skip a single statement depending on a boolean value

3 ビュー (過去 30 日間)
yosef
yosef 2022 年 12 月 15 日
コメント済み: yosef 2022 年 12 月 21 日
I have a statement which is an error depending on some boolean value. Is there a way to make the computer skip the one statement when that boolean is true / false?
Looking for a way to do it in one line and without while or if. Something that reminds this
x = x + (a<=b)*scalar_function(a,b)
  5 件のコメント
Jan
Jan 2022 年 12 月 17 日
@yosef: The name "scalar_function" implies, that this is a function, which replies a scalar. I do not know, what "another statement" should be. Sugar Daddy's suggestion looks efficient. If it does not match your problem, explain the original procedure with more details.
Jan
Jan 2022 年 12 月 19 日
@Sugar Daddy: Stop this.

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

回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 12 月 17 日
piecewise is the only way to selectively execute expressions.
logical times expression still executes the expression. If execution of the expression would generate an error in the situation, you would get the error. If the expression generates infinity under the circumstances then you get 0 times infinite which would be nan. If the expression generates nan under the circumstances you would have 0 times nan.
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 12 月 19 日
%alternative
x = x + scalar_question_colon(a<=b, @()scalar_function(a,b), @()0);
function result = scalar_question_colon(condition, true_handle, false_handle)
if all(condition)
result = true_handle();
else
result = false_handle();
end
end
You can see from the function name I gave that this is only designed to work with scalar operands. This is consistent with your code
x = x + (a<=b)*scalar_function(a,b)
as the * operation is matrix multiplication, also known as "inner product", which requires that at least one side be a scalar or else that the number of columns on the left is the same as the number of rows on the right. If a<=b were a vector then the * operator would fail if scalar_function given vector inputs did not return a scalar.
You can generalize to a non-scalar question_colon operator, but those cases get messier to code, as the context is often that you want to apply the two possibilities to the inputs selectively.
yosef
yosef 2022 年 12 月 21 日
I'm much smarter now. Thank you

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

カテゴリ

Help Center および File ExchangeDevelop Apps Using App Designer についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by