Problem 57735. Easy Sequences 98: One-line Code Challenge - Ternary Operator Function

Ternary operation is a standard construct in most computer languages. The ternary operator assigns value to a variable depending on the result of the condition. For example, we find the following syntax in C and many C-like languages:
y = (p > q) ? m : n;
which means that y is assigned the value of either m or n, depending on whether the statement (p > q) is true or false, respectively.
Unfortunately, Matlab does not have a ternary operator and if we need to get the same effect, we may write the statement this way:
if p > q
y = m;
y = n;
But that is 5 lines of Matlab code versus just a single line in C!
In this problem we are required create the function ternaryFunc, which takes on the following parameters: data values a and b; a conditional function C, that outputs true or false, and functions T and F which are applied to a and b, depending on the value of C(a,b). We can write the function as follows:
function x = ternaryFunc(a,b,C,T,F)
if C(a,b)
x = T(a,b);
x = F(a,b);
NOTE: The following restrictions apply:
  • The function should only have one (1) line of code, excluding the function start line.
  • Semicolons (;) are considered end-of-line characters.
  • Use of if, while and switch statements is not allowed.
  • Regular expressions and string manipulation are not allowed.
  • Use of variable length arguments is not allowed.
HINT: As an exercise you may want to first solve Problem #44243.

Solution Stats

11.25% Correct | 88.75% Incorrect
Last Solution submitted on Jun 06, 2024

Problem Comments

Solution Comments

Show comments

Problem Recent Solvers6

Suggested Problems

More from this Author116

Community Treasure Hunt

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

Start Hunting!