Matrix IIF

Returns first or second expression depending of a condition result
227 Downloads
Updated 23 Sep 2010

View License

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 was internally implemented)
A = (A>4)*100 + (A<=4)*-200

It allows powerful inline matrix operations

Supose A e 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

Cite As

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

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Creating and Concatenating Matrices in Help Center and MATLAB Answers

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.0.0.0