Not as elegant as a C style ternary operator but you can take advantage of the fact that matlab will automatically cast logicals into doubles in this situation. So you can just multiply your desired result for true (r
in this case) by your condition (a > b
), and add that to the product of your desired result for false (i.e. g
) with the not of your condition:
foo = (a > b)*c + (~(a > b))*d
so if we let c = 'r'
and d = 'g'
then all we need to do is cast foo
back to a char
at the end:
char(foo)
or
char((a > b)*'r' + ~(a > b)*'g')
Note that this will only work if c
and d
have the same dimensions (because of the +
)...