Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 852
Lance Roberts Avatar asked Jan 30 '13 19:01

Lance Roberts


People also ask

What are conditional operators in Matlab?

For both if and switch , MATLAB®executes the code corresponding to the first true condition, and then exits the code block. Each conditional statement requires the end keyword.

What is if statement in matlab?

if expression , statements , end evaluates an expression, and executes a group of statements when the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false. The elseif and else blocks are optional.


1 Answers

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

a = b + (c > 0) * c; 

In this case, the operator (c > 0) values 1 (logical type) whenever c > 0 and values to 0 otherwise.

like image 135
Alex Avatar answered Nov 02 '22 01:11

Alex