我想使用类似C的三元运算符,但是在Matlab中,该怎么做?
例如:
a = (test == 'yes') ? c : d
其中,a,c和d是数字,但在Matlab中?
有两种选择:
内联if语句
a = (test == 'yes') * c;
内联if else语句
a = (test == 'yes') * c + (test ~= 'yes') * d;
或更整洁地:
t = test == 'yes'; a = t * c + ~t * d;
这在数字情况下有效,因为test == 'yes'
根据是否为真将其强制转换为0或1-然后可以将其乘以所需的结果(如果它们是数字)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句