How to implement a conditional function indexed by a specified frequency
조회 수: 2 (최근 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!