Almost a ternary conditional operator

版本 1.1.0.0 (2.1 KB) 作者: Richie Cotton
Function for vectorised if-else statements.
2.0K 次下载
更新时间 2008/12/8

查看许可证

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.

引用格式

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

MATLAB 版本兼容性
创建方式 R2008a
兼容任何版本
平台兼容性
Windows macOS Linux
类别
Help CenterMATLAB Answers 中查找有关 Arithmetic Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!
版本 已发布 发行说明
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.