Almost a ternary conditional operator

Function for vectorised if-else statements.
2K Downloads
Aktualisiert 8. Dez 2008

Lizenz anzeigen

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.

Zitieren als

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

Kompatibilität der MATLAB-Version
Erstellt mit R2008a
Kompatibel mit allen Versionen
Plattform-Kompatibilität
Windows macOS Linux
Kategorien
Mehr zu Arithmetic Operations finden Sie in Help Center und MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Veröffentlicht Versionshinweise
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.