How can i create an if-function with probability p ?

Hi, im quite new in all this, i hope someone can help me.
I should generate a function that with probability p calculates for example y=2x and with probability 1-p y = 5x. I don't know how to do it but i thought of creating a variable, lets call it C, that equals 1 with probability p and something else with p-1 or something similar and then create an if function with
if C=1
y=2x
else
y=5x
But is there the possibility to create something like C and how? Or is there an easier way to do this?
Sorry, i hope this was clear and thanks in advance!
Best, Nina

3 件のコメント

James Tursa
James Tursa 2015 年 4 月 17 日
Did you bother reading the answer that was already posted on the Newsgroup?
Nina Gerber
Nina Gerber 2016 年 2 月 3 日
thanks & sorry for bothering i haven't found the answer!
Walter Roberson
Walter Roberson 2016 年 2 月 3 日
I confirm that Roger's solution works.
For example,
x = 1 : 10;
p = 0.2;
for tryno = 1 : 8
if rand <= p
y = 2 * x
else
y = 5 * x
end
end
You can see that the answer is not always the same

サインインしてコメントする。

回答 (1 件)

Roger Stafford
Roger Stafford 2015 年 4 月 17 日

1 投票

if rand<=p
y = 2*x;
else
y = 5*x;
end

2 件のコメント

Nina Gerber
Nina Gerber 2015 年 4 月 17 日
Thanks, but If i run the function like this it always returns the else command, so y=5*x what im i doing wrong?
Roger Stafford
Roger Stafford 2015 年 4 月 17 日
編集済み: Roger Stafford 2015 年 4 月 18 日
That would only be true if you reset the "seed" for 'rand' processing using 'rng' each time you called 'rand', or if you shut off the computer each time.

サインインしてコメントする。

タグ

質問済み:

2015 年 4 月 17 日

コメント済み:

2016 年 2 月 3 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by