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
Is there an operator or function that will let me do these conditionals inline in MATLAB code?
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
Is there an operator or function that will let me do these conditionals inline in MATLAB code?
There is now a
tern
function on the MathWorks file exchange: http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs/content/tern.mThe code is reproduced here:
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 toNaN
. 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: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.
Others have said already that there is no ternary
?:
operator in Matlab. As a solution I suggest this function, which takes three functions instead of values. Therefore the amount of unnecessary calculations is minimized and you can check conditions before starting calculations, e.g. if a value is really numeric, or finite, or nonzero:Use it like this:
How about simply using the fact that MATLAB automatically converts variable types when required by the operation? E.g., logical to double.
If your variables are scalar double, your code, I believe, can be replaced by
In this case, the operator
(c > 0)
values1
(logical type) wheneverc > 0
and values to0
otherwise.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 outcomesa
andb
:For a more advanced solution, there's a way to create an inline function that can even do elseif, as outlined in this blog post about anonymous function shenanigans:
You use this function as
where you replace the dots with any number of additional condition/value pairs.
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.There is no built-in solution for this, but you can write an IIF yourself.