## Matrix IIF

version 1.2.0.0 (1.35 KB) by
Returns first or second expression depending of a condition result

Updated 30 Sep 2010

iif(Cond, ExprA,ExprB) is inspired in a traditional function from Visual Basic that receives a condition and returns ExprA or ExprB, depending of COND evaluation (true or false)

As MatLab is a matrix language, iif was implemented as a matrix function.

Suppose that COND compares a matrix with a number so COND is a matrix of same dimensions. The matrix result contains just A or B elements, depending if COND is true ("A") or false ("B")

Example:
A = [ 1 5 8 3 ];
disp( iff(A > 4, 100,-200) )

The display is
[ -200 100 100 -200 ]

Normally it can be done of a less intuitive way
(the method that iif was internally implemented)
A = (A>4)*100 + (A<=4)*-200

It allows powerful inline matrix operations:

Supose A and B two scores set from a student, the average system is the mean, with the biggest score with weight 2 and the other with weight 1.

A =[7 8 3 4];
B = [6 7 7 9];
disp(iif(A>B,(2*A+B)/3, (2*B+A)/3))

Result is
[6.66 7.66 5.66 7.33]

The alternative way is (and the form that was internally implemented)
(A>B).*(2*A+B)/3 + (A<=B).*(2*B+A)/3

At last, it works if COND is a scalar condition.

For instance

a='Paul';
b='John';
disp(iif(strcmpi(a,b),'equal','different'))

Shows 'different'

### Cite As

Paulo Buchsbaum (2022). Matrix IIF (https://www.mathworks.com/matlabcentral/fileexchange/28811-matrix-iif), MATLAB Central File Exchange. Retrieved .

##### MATLAB Release Compatibility
Created with R2009b
Compatible with any release
##### Platform Compatibility
Windows macOS Linux