File Exchange

image thumbnail

Almost a ternary conditional operator

version 1.1 (2.06 KB) by

Function for vectorised if-else statements.



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.

Comments and Ratings (7)


James (view profile)

Sorry, my first post was accidentally deleted.

each of these operations can be accomplished with a single line:

first example:


second example (where ii = (1:1000000)' and bb = rand(numel(ii),1)):

(bb>0.5)*4 + (bb<=0.5).*(ii+1);

running this is even faster:

tic; (bb>0.5)*4 + (bb<=0.5).*(ii+1); toc
Elapsed time is 0.072034 seconds.

The third example:

x = condn*3 + ~condn*4;

No function-calling overhead, no new stack frame, and written in a single line.


James (view profile)

Apologies on my last post, in the second example, it should read "ii=1:1000000".

Jan Simon

Jan Simon (view profile)

I cannot follow your Example 2:
for i=1:100000; if 1; 4; else 1+i; end; end
truth = rand(1000000,1)< 0.5; vif(truth , 4, 1+i);
You compare the speed of the first part, which computes nothing in 1e5 loops, with the 2nd, which creates a vector of 1e6 random [4 +0i] and [1 +1i].

Mukhtar Ullah

You are right. I did not realize that the variable 'yes' is already there as input.

Yi Cao

Why not use these two sentences:


Mukhtar Ullah

Good idea. However, I would have written it like this (for efficiency):

if ~islogical(truth)
truth = logical(truth);
out = zeros(size(truth));
out(:) = no;
out(truth) = yes;

Yi Cao

This is a good idea. However, if truth = logical(truth) on line 37 is replaced by truth = ~~truth will improve the speed. You even can remove the if line completely.



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

Bug fix: Infinite inputs now handled correctly.

1. New functionality

2. Code optimisation based upon review comments.

MATLAB Release
MATLAB 7.6 (R2008a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Win prizes and improve your MATLAB skills

Play today