function of two uniformly random variables

5 vues (au cours des 30 derniers jours)
Ruslan Askarov
Ruslan Askarov le 29 Avr 2023
Déplacé(e) : Torsten le 2 Mai 2023
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

Réponse acceptée

John D'Errico
John D'Errico le 29 Avr 2023
Modifié(e) : John D'Errico le 29 Avr 2023
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 commentaire
Ruslan Askarov
Ruslan Askarov le 2 Mai 2023
Déplacé(e) : Torsten le 2 Mai 2023
Thank you so much. It's a great job. You explained each step. I will learn how to use functions.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by