This function has two purposes:
1. Loops of simple if-else statements can be avoided through vectorisation, providing a performance boost.
% vif(eye(3), 4, 1)
% ans =
% 4.0000 1.0000 1.0000
% 1.0000 4.0000 1.0000
% 1.0000 1.0000 4.0000
% 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.
% x = vif(condn, 3, 4);
% % is easier to type than
% if condn
% x = 3;
% x = 4;
Updates: char and infinite inputs now correctly handled.
Sorry, my first post was accidentally deleted.
each of these operations can be accomplished with a single line:
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.
Apologies on my last post, in the second example, it should read "ii=1:1000000".
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].
You are right. I did not realize that the variable 'yes' is already there as input.
Why not use these two sentences:
Good idea. However, I would have written it like this (for efficiency):
truth = logical(truth);
out = zeros(size(truth));
out(:) = no;
out(truth) = yes;
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.
Bug fix: Infinite inputs now handled correctly.
1. New functionality
2. Code optimisation based upon review comments.