是否有可以像 VBA 的 IIF 一样内联放置的 Matlab 条件 IF 运算符
在 VBA 中,我可以执行以下操作:
In VBA I can do the following:
A = B + IIF(C>0, C, 0)
所以如果 C>0 我得到 A=B+C
和 CA=B
so that if C>0 I get A=B+C
and C<=0 I get A=B
是否有运算符或函数可以让我在 MATLAB 代码中内联执行这些条件?
Is there an operator or function that will let me do these conditionals inline in MATLAB code?
Matlab 中没有三元运算符.当然,您可以编写一个函数来执行此操作.例如,以下函数作为 iif
工作,条件为 nd 输入,结果为 a
和 b
的数字和单元格:
There is no ternary operator in Matlab. You can, of course, write a function that would do it. For example, the following function works as iif
with n-d input for the condition, and with numbers and cells for the outcomes a
and b
:
function out = iif(cond,a,b)
%IIF implements a ternary operator
% pre-assign out
out = repmat(b,size(cond));
out(cond) = a;
对于更高级的解决方案,有一种方法可以创建一个甚至可以执行 elseif 的内联函数,如 这篇关于匿名函数恶作剧的博文:
iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
您将此功能用作
iif(condition_1,value_1,...,true,value_final)
用任意数量的附加条件/值对替换点.
where you replace the dots with any number of additional condition/value pairs.
它的工作方式是从值中选择第一个条件为真的值.2*find(),1,'first')
提供值参数的索引.
The way this works is that it picks among the values the first one whose condition is true. 2*find(),1,'first')
provides the index into the value arguments.