我想使用交流式三元运算符,但在Matlab中,如何做到这一点?
例如:
a = (test == 'yes') c : d
Run Code Online (Sandbox Code Playgroud)
其中a,c和d是数字但在Matlab中?
Jam*_*mes 10
有两种选择:
内联if语句
a = (test == 'yes') * c;
Run Code Online (Sandbox Code Playgroud)
内联if else语句
a = (test == 'yes') * c + (test ~= 'yes') * d;
Run Code Online (Sandbox Code Playgroud)
或者更整洁:
t = test == 'yes'; a = t * c + ~t * d;
Run Code Online (Sandbox Code Playgroud)
这适用于数字情况,因为test == 'yes'它被转换为0或1,具体取决于它是否为真 - 然后可以乘以期望的结果(如果它们是数字).
提供替代方案:
t = xor([false true], isequal(test, 'yes')) * [c; d]
Run Code Online (Sandbox Code Playgroud)
或者如果你想要
ternary = @(condition, trueValue, falseValue)...
xor([false true], condition) * [trueValue; falseValue];
...
t = ternary(isequal(test, 'yes'), c, d);
Run Code Online (Sandbox Code Playgroud)