Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does matlab have a ternary operator? [duplicate]

Tags:

matlab

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?

like image 754
James Avatar asked Jan 20 '14 14:01

James


2 Answers

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).

like image 128
James Avatar answered Nov 08 '22 10:11

James


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);
like image 5
Rody Oldenhuis Avatar answered Nov 08 '22 11:11

Rody Oldenhuis