function of two uniformly random variables

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Mathematics and Optimization 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by