5

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?

vitaminace33
  • 133
  • 6
James
  • 30,496
  • 19
  • 86
  • 113

2 Answers2

10

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

James
  • 30,496
  • 19
  • 86
  • 113
  • While this is not quite the same thing, it is close enough and should get the job done. And did you answer your own question within a minute of posting. – MZimmerman6 Jan 20 '14 at 15:06
  • 1
    @MZimmerman6 Yes, it did the job for me. I just wanted to share it because I thought it was quite good at the time :) – James Feb 07 '14 at 00:50
  • This will fail if any of values of t is NaN or +/-Inf. – tstanisl Feb 07 '20 at 08:10
5

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);
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96