How to implement a conditional function indexed by a specified frequency
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponses (1)
Guillaume
le 16 Mar 2016
Modifié(e) : Guillaume
le 16 Mar 2016
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.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!