Lan*_*rts 27 matlab vba ternary-operator conditional-operator iif
在VBA中,我可以执行以下操作:
A = B + IIF(C>0, C, 0)
Run Code Online (Sandbox Code Playgroud)
所以,如果C> 0,我得到A=B+C
,C <= 0,我得到A=B
是否有一个运算符或函数可以让我在MATLAB代码中内联这些条件?
小智 36
如何简单地使用MATLAB在操作需要时自动转换变量类型的事实呢?例如,逻辑加倍.
如果您的变量是标量加倍,我相信您的代码可以替换为
a = b + (c > 0) * c;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,运算符(c > 0)
值1
(逻辑类型)c > 0
,0
否则为值.
Jon*_*nas 26
Matlab中没有三元运算符.当然,您可以编写一个可以执行此操作的函数.例如,下面的功能的作用类似于iif
具有用于条件第二输入,和与用于结果的数字和细胞a
和b
:
function out = iif(cond,a,b)
%IIF implements a ternary operator
% pre-assign out
out = repmat(b,size(cond));
out(cond) = a;
Run Code Online (Sandbox Code Playgroud)
对于更高级的解决方案,有一种方法可以创建一个甚至可以执行elseif的内联函数,如本博客文章中关于匿名函数shenanigans所述:
iif = @(varargin) varargin{2*find([varargin{1:2:end}], 1, 'first')}();
Run Code Online (Sandbox Code Playgroud)
您使用此功能
iif(condition_1,value_1,...,true,value_final)
Run Code Online (Sandbox Code Playgroud)
用任意数量的附加条件/值对替换点.
这种方法的工作方式是在值中选择条件为真的第一个值. 2*find(),1,'first')
提供值参数的索引.
没有内置的解决方案,但你可以自己编写一个IIF.
function result=iif(cond, t, f)
%IIF - Conditional function that returns T or F, depending of condition COND
%
% Detailed
% Conditional matrix or scalar double function that returns a matrix
% of same size than COND, with T or F depending of COND boolean evaluation
% if T or/and F has the same dimensions than COND, it uses the corresponding
% element in the assignment
% if COND is scalar, returns T or F in according with COND evaluation,
% even if T or F is matrices like char array.
%
% Syntax
% Result = iif(COND, T, F)
% COND - Matrix or scalar condition
% T - expression if COND is true
% F - expression if COND is false
% Result - Matrix or scalar of same dimensions than COND, containing
% T if COND element is true or F if COND element is false.
%
if isscalar(cond)
if cond
result = t;
else
result = f;
end
else
result = (cond).*t + (~cond).*f;
end
end
Run Code Online (Sandbox Code Playgroud)
其他人已经说过?:
Matlab中没有三元运算符.作为一个解决方案,我建议使用这个函数,它取三个函数而不是值.因此,最小化了不必要的计算量,您可以在开始计算之前检查条件,例如,如果值实际上是数字,有限或非零:
function [ out ] = iif( condition, thenF, elseF, in, out)
%iif Implements the ternary ?: operator
% out = iif (@condition, @thenF, @elseF, in[, out])
%
% The result is equivalent to:
% condition(x) ? thenF(x) : elseF(x)
%
% The optional argument out serves as a template, if the output type is
% different from the input type, e.g. for mapping arrays to cells and
% vice versa.
%
% This code is in the public domain.
mask = condition(in);
if nargin <= 4
out = in;
end
if sum(mask)
out(mask) = thenF(in(mask));
end
if sum(~mask)
out(~mask) = elseF(in(~mask));
end
end
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
f = @(y)(iif(@(x)(x > 3), @(x)(x.^2), @(x)(x/2), y))
f(linspace(0,6,10))
Run Code Online (Sandbox Code Playgroud)