0

I wrote this code in Matlab and I am looking for equivalent code in Python. Can someone help? The code is to generate N Points inside a rectangle of side LxL with Gaussian Distribution. The code was obtained from this link: gaussian_inside_rectangle

function ans = randn_rect( N, sigma, L )
ans = zeros(0,2);
while size(ans,1) < N,
   pts = sigma * randn( ceil(1.25*(N-size(ans,1))), 2 );    
   pts = pts(all(abs(pts)<L/2,2),:);
   ans = [ ans ; pts ];
end
ans = ans(1:N,:);
3
  • Please fix your code. "enter code here" fragment is clearly alien :^) Commented Apr 7, 2014 at 14:10
  • Sorry but I don't understad your comment? Commented Apr 7, 2014 at 15:12
  • Your code is not valid MATLAB language. You probably failed to clear the "enter code here" phrase when inserting it. Commented Apr 8, 2014 at 6:57

1 Answer 1

1

So you want to sample N 2-dimensional points from a truncated normal distribution? Gladly, scipy comes with that one built-in.

This generates a N*2 numpy array points with random points:

from scipy.stats import truncnorm
import numpy as np

N = 1000
L = 5.0
mu = 4.0
sigma = 0.8

lower, upper = 0, L

X = truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)

points = np.reshape(X.rvs(2*N), (N, 2))

The code was adapted from this answer.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot, I run the code for N =10 and L = 100, I have obtaied these points: [[ 3.12334787 3.70831649] [ 3.58128416 5.73846664] [ 4.3797186 4.03120809] [ 5.30411406 4.4329382 ] [ 4.50553099 4.00487617] [ 2.77175744 4.44342638] [ 4.18085468 3.42912618] [ 3.64834852 3.32652222] [ 4.19270372 4.1313387 ] [ 4.65842432 2.40781954]] all the values are arround 4 even if L is 100 ??
If you didn't change mu, then yes, your values should be centered around 4. The array you've posted looks good.
Then, I should set mu to 100
I mean that the values are not ditributed all over the area of 100x100. Points are all very close to point(4,4)
Why would they distributed all over the area? The distribution in the example has a standard deviation of 0.8. It appears that you don't really know what a normal (Gaussian) distribution is. You should read up on that first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.