I would like to use a C-like ternary operator but in Matlab, how can this be done?
For example:
a = (test == 'yes') ? c : d
where a,c and d are numeric but in Matlab?
A couple of options:
Inline if statement
a = (test == 'yes') * c;
Inline if else statement
a = (test == 'yes') * c + (test ~= 'yes') * d;
or more neatly:
t = test == 'yes'; a = t * c + ~t * d;
This works in the numeric case since test == 'yes'
is cast to 0 or 1 depending on whether it's true or not - which can then be multiplied by the desired outcomes (if they are numeric).
To provide an alternative:
t = xor([false true], isequal(test, 'yes')) * [c; d]
or if you want
ternary = @(condition, trueValue, falseValue)...
xor([false true], condition) * [trueValue; falseValue];
...
t = ternary(isequal(test, 'yes'), c, d);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With