Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF

后端 未结 10 1299
滥情空心
滥情空心 2020-12-01 11:06

In VBA I can do the following:

A = B + IIF(C>0, C, 0)

so that if C>0 I get A=B+C and C<=0 I get A=B

10条回答
  •  暖寄归人
    2020-12-01 11:34

    This is more of an addenum to Alex's answer.

    Alex's method doesn't work when you want to return inf

    In these cases you often end up getting a 0*inf figure, which MATLAB will evaluate to NaN. Problematic... We can avoid this multiplication using a lookup instead.

    As an example, a useful barrier function in convex optimization is something that behaves like log everywhere positive, and -inf elsewhere. Here is how you might create such a function using a lookup:

    INF_CONDITION = [0, inf];
    fn_logbr = @(x) (x>0)*log(x) - INF_CONDITION( 1+(x<=0) )
    

    Inline conditionals are a hack, and you lose lazy evaluation. You have to be careful. However, having semantic code is really nice, and its easier to share your code when you can't guarantee everyone's environments are the same.

提交回复
热议问题