フィルターのクリア

How to Write all of an if-statement in a Single Lline?

733 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2016 年 8 月 16 日
編集済み: Angelo Yeo 2023 年 7 月 8 日
Is there any way to write all of an if-statement in a single line?
if A == 1 B = 2 elseif B = 3 end

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 8 月 16 日
編集済み: Azzi Abdelmalek 2016 年 8 月 16 日
if A ==1 B = 2, else B = 3, end
But what is the aim of this?
  5 件のコメント
Steven Lord
Steven Lord 2021 年 4 月 13 日
Consider writing a "logme" function.
function logme(messageToLog)
verbose = true;
if verbose
fprintf('%s', messageToLog)
end
end
Now your code will contain calls to logme.
logme("Diagnostic message #1")
If you want to run without displaying these messages, change the definition of verbose inside logme. You could potentially also modify logme to log those messages not to the screen but to a log file without changing the callers of logme.
Angelo Yeo
Angelo Yeo 2023 年 7 月 8 日
編集済み: Angelo Yeo 2023 年 7 月 8 日
If you want to set up if-else statement with a single line and make it into an inline funciton, you can think of such a thing.
ternary = @(varargin) varargin{end - varargin{1}};
ternary(true,'yes','no') % If the first argument is true, the result becomes 'yes'
ans = 'yes'
ternary(false,'yes','no') % If the first argument is false, the result becomes 'no'
ans = 'no'

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

その他の回答 (1 件)

KarlHoff
KarlHoff 2021 年 10 月 20 日
You can employ logicals as factors toggling between 0 and 1:
B = 2 + 1*(A~=1);
%or
%B = 3 + (-1)*(A==1) ; % just roles reversed - depending on taste
This approach works whenever your if-statement just discriminates between two versions of a single assignment to one and the same variable as your example does.
I personally find this particular useful if there is a base value (here 2) and some delta added conditionally (here, +1 to obtain 3). You can also extend for further conditions.
  2 件のコメント
Reno Filla
Reno Filla 2021 年 12 月 9 日
The problem is if you want to get NaN on the case of, for example A==1
2+NaN*(A==1) doesnt work because 0*NaN return NaN just as 1*NaN does.
Also employing the NaN() function like
2+NaN(A==1) doesnt help since NaN(0) returns [] and canot be added to a scalar.
Any ideas?
KarlHoff
KarlHoff 2021 年 12 月 10 日
How about
0/(A-1) + 3 %returns different numeric values for different A ~= 1
or
0/( (A==1)-1 ) + 3 % returns 3 for all A ~= 1

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

カテゴリ

Help Center および File ExchangeCOM Component Integration についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by