Ternary: Inline if/else and switch/case

Version 1.0.0 (1.42 KB) by David
An inline conditional. Can be used as boolean (if/else) or multichoice (switch/case)
Updated 26 Oct 2020

View License

An inline conditional. Can function as an if/else of as a switch/case.

If/else behavior:
tern(cond,a,b) returns: a if cond is true, else returns b

Switch/case behavior (>3 arguments):
tern(s,case1,value1,..,caseN,valueN,<defaultValue>), same as:
switch s
case case1
return value1
case caseN:
return valueN
return defaultValue (default = NaN)

If/else behavior:
disp(tern(val>0,'value is positive!', 'value is negative'));

Switch/case behavior:
disp(tern(val,1,'value is one!', 2, 'value is two!', 'values is not 1 or 2'));

Cite As

David (2024). Ternary: Inline if/else and switch/case (https://www.mathworks.com/matlabcentral/fileexchange/81863-ternary-inline-if-else-and-switch-case), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2020b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes