Is there a one-liner in MATLAB for this?
if a > b
foo = 'r';
else
foo = 'g';
end
There is no syntactic sugar for one-line if-statements in MatLab, but if your statement is really simple you could write it in one line.
I used to have one-line if-statements like that in my old project:
if (k < 1); k = 1; end;
In your case it'll look something like:
if a > b; foo = 'r'; else; foo = 'g'; end;
or, if you don't like semicolons
if a > b, foo = 'r'; else, foo = 'g'; end
Not as pretty as you may have expected, though.
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 +
)...
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