How to implement a conditional function indexed by a specified frequency
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Guillaume
2016-3-16
编辑:Guillaume
2016-3-16
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!