2014-01-20 330 views

回答

6

几个选项:

内嵌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 - 然后可以将其乘以所需结果(如果它们是数字)。

+0

虽然这是不太一样的东西,它是足够接近,应该把工作做好。你是否在一分钟内回答你自己的问题? – MZimmerman6

+1

@ MZimmerman6是的,它为我完成了工作。我只是想分享它,因为我认为这是相当不错的:) – James

3

为了提供一种替代方案:

t = xor([false true], isequal(test, 'yes')) * [c; d] 

,或者如果你想

ternary = @(condition, trueValue, falseValue)... 
    xor([false true], condition) * [trueValue; falseValue]; 

... 

t = ternary(isequal(test, 'yes'), c, d);