Almost a ternary conditional operator

Function for vectorised if-else statements.
2K descargas
Actualizado 8 dic 2008

Ver licencia

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.

Citar como

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

Compatibilidad con la versión de MATLAB
Se creó con R2008a
Compatible con cualquier versión
Compatibilidad con las plataformas
Windows macOS Linux
Categorías
Más información sobre Arithmetic Operations en Help Center y MATLAB Answers.

Community Treasure Hunt

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

Start Hunting!
Versión Publicado Notas de la versión
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.