Almost a ternary conditional operator

Function for vectorised if-else statements.
2K Downloads
Updated 8 Dec 2008

View License

This function has two purposes:
1. Loops of simple if-else statements can be avoided through vectorisation, providing a performance boost.

% Example:
% vif(eye(3), 4, 1)
% ans =
%
% 4.0000 1.0000 1.0000
% 1.0000 4.0000 1.0000
% 1.0000 1.0000 4.0000

Example 2:
% tic; for i=1:100000; if 1; 4; else 1+i; end; end; toc
% Elapsed time is 0.831261 seconds.
%
% truth = rand(1000000,1)< 0.5;
% tic; vif(truth , 4, 1+i); toc
% Elapsed time is 0.097463 seconds.

2. Syntax for individual if-else statements can be simplified, in a manner reminiscent of a C-style ternary conditional operator, at a slight performance loss.

Example 3:
% x = vif(condn, 3, 4);
% % is easier to type than
% if condn
% x = 3;
% else
% x = 4;
% end

Updates: char and infinite inputs now correctly handled.

Cite As

Richie Cotton (2024). Almost a ternary conditional operator (https://www.mathworks.com/matlabcentral/fileexchange/18800-almost-a-ternary-conditional-operator), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2008a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Arithmetic Operations 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.1.0.0

Silly bug fixed.
Also now warns if second or third input is complex.

1.0.0.0

Bug fix: char inputs no longer coerced to numeric. More input checking.