How to implement a conditional function indexed by a specified frequency
Show older comments
I wish to call a function indexed by a designated label (i.e 1,2,3 or 4) across 1000 trials with the frequency of (3,1,1,1) respectively.
i.e the function designated by 1 is 3 times more likely to be called than functions designated by 2,3 and 4 respectively. I was thinking of initialising a vector of 1000 integers (between 1,2,3 and 4) accoridng to the following code:
R = randsample([1 2 3 4], 1000, true, [3 1 1 1])
...Before calling a for loop as follows (forgive the pseudocode);
for i=1:length®;
if '1', then;
'function 1'
if '2', then;
'function 2'
if '3', then;
'function 3'
if '4', then;
'function 4'
... May someone assist me in writing the code (minus specific functions of course). Many thanks.
Answers (1)
functionstocall = {@sin, @cos, @log, @exp}; %4 functions for demo
chosenfunction = randsample([1 2 3 4], 1000, true, [3 1 1 1]);
for iter = 1:numel(chosenfunction)
x = rand;
y(iter) = functionstocall{chosenfunction(iter)}(x) %call function index by chosenfunction(iter)
end
No need for a if, just simple indexing.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!