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;
else
y = n;
end
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);
else
x = F(a,b);
end
end
-------------
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.
-------------
Solution Stats
Problem Comments
-
2 Comments
Dyuman Joshi
on 28 Feb 2023
It's a shame that MATLAB does not give an error when dividing numeric values with 0.
Ramon Villamangca
on 28 Feb 2023
That's true. That's why I like it. It seldom crash.
Solution Comments
Show commentsProblem Recent Solvers6
Suggested Problems
-
Determine whether a vector is monotonically increasing
20698 Solvers
-
270 Solvers
-
568 Solvers
-
Who has power to do everything in this world?
440 Solvers
-
336 Solvers
More from this Author116
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!