필터 지우기
필터 지우기

How to write function to generate gaussian distribution of normal numbers with specified mean, variance and number of values?

조회 수: 12 (최근 30일)
I am using MATLAB R2020a Psychtoolbox on Mac OS. I found the following code here to generate a gaussian distribution of random numbers and used it to write a function to specify the mean, variance, upper and lower limits and number of values, however it doesn't generate the numbers.
function distribution(va, mu, ul, ll, nvals)
multiplier=10;
x = mu + randn(multiplier*nvals,1)*sqrt(va); % Generate sufficient random numbers
idx = (ll <= x) & (x <= ul); % Extract the value in the given range [min max]
while sum(idx)<nvals
multiplier=multiplier+1;
x = mu + randn(multiplier*nvals,1)*sqrt(va); % Generate sufficient random numbers
idx = (ll <= x) & (x <= ul); % Extract the value in the given range [min max]
end
x = x(idx);
x = x(1:nvals); % Extract numbers
end

채택된 답변

Jeff Miller
Jeff Miller 2020년 8월 19일
you must return something from your function:
function x = distribution(va, mu, ul, ll, nvals)
  댓글 수: 3
Jeff Miller
Jeff Miller 2020년 8월 20일
I'm guessing that with some numbers the code just takes a very long time to run. For example, with mean 0 and variance 1, it would take a long time to find numbers between the bounds of +10 and +11, because those are very low probability. You could speed up your function by keeping the numbers between ll and ul and only generating replacements (inside the loop) for those outside those boundaries.
Better still, you might look into MATLAB's truncated normal distribution objects. These will let you do what you want much more directly, something like
n = makedist('normal','mu',mu,'sigma',sqrt(va))
t = truncate(n,ll,ul)
x = random(t,nvals,1)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Timing and presenting 2D and 3D stimuli에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by