Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner for if then [duplicate]

Is there a one-liner in MATLAB for this?

if a > b
    foo = 'r';
else
    foo = 'g';
end
like image 206
Sibbs Gambling Avatar asked Nov 27 '22 16:11

Sibbs Gambling


2 Answers

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.

like image 175
Leonid Beschastny Avatar answered Dec 10 '22 10:12

Leonid Beschastny


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

like image 42
Dan Avatar answered Dec 10 '22 10:12

Dan