How to Write all of an if-statement in a Single Lline?
Show older comments
Is there any way to write all of an if-statement in a single line?
if A == 1 B = 2 elseif B = 3 end
Accepted Answer
More Answers (1)
KarlHoff
on 20 Oct 2021
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 Comments
Reno Filla
on 9 Dec 2021
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
on 10 Dec 2021
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
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!