如果那么单线 [英] One-liner for if then
问题描述
MATLAB中是否有单行内容?
Is there a one-liner in MATLAB for this?
if a > b
foo = 'r';
else
foo = 'g';
end
推荐答案
不像C那么优雅样式三元运算符,但您可以利用matlab在这种情况下自动将逻辑转换为双精度的事实。因此,您可以根据您的条件( a> b
)将您想要的结果乘以true(在这种情况下为 r
) ),并使用 not 条件将其添加到您想要的结果的产品中(即 g
):
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
所以如果我们让 c ='r'
和 d ='g'
然后我们需要做的就是将 foo
转换回 char
最后:
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)
或
char((a > b)*'r' + ~(a > b)*'g')
请注意,这仅在<$ c时有效$ c> c 和 d
具有相同的尺寸(因为 +
)。 ..
Note that this will only work if c
and d
have the same dimensions (because of the +
)...
这篇关于如果那么单线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!