function of two uniformly random variables

2 ビュー (過去 30 日間)
Ruslan Askarov
Ruslan Askarov 2023 年 4 月 29 日
移動済み: Torsten 2023 年 5 月 2 日
Given two independent uniform random variables X,Y ∼ U{[0, 1]}, consider the random variable
Z = g(X,Y ) for g(x, y) = sqrt(−2 ln(x)) * sin(2*pi*y).
My code:
x = rand(1,10000);
y = rand(1,10000);
z=rand(g,10000);
histogram(z,200);
function g(x,y)
g = sqrt(-2*log(x))*sin(2*pi*y);
end
I'm not sure about function, please help me

採用された回答

John D'Errico
John D'Errico 2023 年 4 月 29 日
編集済み: John D'Errico 2023 年 4 月 29 日
I think you need to learn how to write a function. You also seriously need to learn about the dotted operators. What you wrote for g was completely wrong, and is why I said both of those things.
Next, z is irrelevant in all of this, so I dropped it.
x = rand(1,10000);
y = rand(1,10000);
x and y are VECTORS. In the operations you will do, you want to compute products of each element of those vectors, and have a result that is also 1x10000. In that case, you NEED to learn what the dotted operators do, thus the .* , ./ and .^ operators.
I'm not really sure why it is you felt the need to write a function at all. This will suffice:
g = sqrt(-2*log(x)).*sin(2*pi*y);
That creates a vector g. Note my use of .* in the middle there. 2*pi*y does not need the dots, because you can always multiply a vector with a scalar. The same applies to -2*log(x). But I COULD have written it as:
g = sqrt(-2.*log(x)).*sin(2.*pi.*y);
The spare dots do not hurt there, though I'd need to think about if 2.*pi.*y is parsed as (2.)*pi.*y or (2).*pi.*y.
COULD you have used a function? Yes, of course. First, I'd write it as a function handle.
g1 = @(x,y) sqrt(-2*log(x)).*sin(2*pi*y);
Now we could use g1 to compute the result. Note my use of the .* operator there again, still necessary.
hist(g1(x,y),200)
Finally, you COULD have written an m-file function. See that I do not assign the computation to the name of the function as you did. But we could also have used g2 now.
hist(g2(x,y),200)
So ANY of those options would have worked.
function result = g2(x,y)
result = sqrt(-2*log(x)).*sin(2*pi*y);
end
I would seriously suggest learning about functions though. You will need them.
  1 件のコメント
Ruslan Askarov
Ruslan Askarov 2023 年 5 月 2 日
移動済み: Torsten 2023 年 5 月 2 日
Thank you so much. It's a great job. You explained each step. I will learn how to use functions.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics and Optimization についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by