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 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