Azzera filtri
Azzera filtri

function of two uniformly random variables

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

John D'Errico
John D'Errico il 29 Apr 2023
Modificato: John D'Errico il 29 Apr 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 Commento
Ruslan Askarov
Ruslan Askarov il 2 Mag 2023
Spostato: Torsten il 2 Mag 2023
Thank you so much. It's a great job. You explained each step. I will learn how to use functions.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by