One-liner for if then [duplicate]

天大地大妈咪最大 提交于 2019-12-19 04:38:21

问题


Is there a one-liner in MATLAB for this?

if a > b
    foo = 'r';
else
    foo = 'g';
end

回答1:


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




回答2:


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.




回答3:


Try to avoid using if statements in matlab, and just convert your logic to (vector) math:

foo = 1 + (a <= b)

Edit:

For the more general case, of assigning 'r' or 'g', you can use:

col = {'r', 'g'};
foo = col(1 + (a > b));

So for example with an isGreen boolean you could do:

foo = col(1 + isGreen);

This could also be a boolean returning function

foo = col(1 + isGreen(a))


来源:https://stackoverflow.com/questions/27561881/one-liner-for-if-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!