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)
9 Downloads
Updated 26 Oct 2020

View License

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

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
otherwise:
return defaultValue (default = NaN)

Examples:
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 (2026). Ternary: Inline if/else and switch/case (https://uk.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
Version Published Release Notes
1.0.0