how to generate random number in a rectangle like this?

6 views (last 30 days)
the inscribed rectangle has length 4 and width 2. The shadow part can appear randomly. How to achieve that using MATLAB?
Your help would be highly appreciated!
  3 Comments
William Rose
William Rose on 3 Nov 2022
Let us assume the center of the goal is at 0,0. The radius is R=sqrt(5). Generate 1000 points, uniformly distributed within this circle:
N=1000; R=sqrt(5);
r=R*sqrt(rand(1,N));
theta=2*pi*rand(1,N);
x=r.*cos(theta);
y=r.*sin(theta);
plot(x,y,'rx');
axis equal; grid on
xticks([-3:3]); yticks([-3:3])
Now lets find how many shots are in gray1: x=(-1,1), y=(-1,1)
gray1=sum((x>=-1 & x<1) & (y>=-1 & y<1));
gray2=sum((x>=-2 & x<-1) & (y>=0 & y<1)) + sum((x>=-1 & x<0) & (y>=-1 & y<0));
gray3=sum((x>=1 & x<2) & (y>=0 & y<1)) + sum((x>=0 & x<1) & (y>=-1 & y<0));
gray4=sum((x>=-2 & x<0) & (y>=-1 & y<0));
gray5=sum((x>=0 & x<2) & (y>=-1 & y<0));
fprintf('Gray1=%d, gray2=%d, gray3=%d, gray4=%d, gray5=%d\n',...
gray1,gray2,gray3,gray4,gray5)
Gray1=265, gray2=137, gray3=112, gray4=139, gray5=117
Since the shots are uniformly distributed, we expect twice as many shots in gray1 than in each of the other regions, since gray1 has twice the area of each other region. The results appear to be what we expect.

Sign in to comment.

Accepted Answer

William Rose
William Rose on 2 Nov 2022
@Daniel Niu, I will assume that there are 5 equally likely options, and that for each option, you want to pick a random point in the gray region.
Then you can do it with two random steps:
1. Pick a random integrer in [1,5]. The tells you which of the 5 cases you are currently using.
2. Pick a random 2D point in the gray region selected by step 1.
When doing step 2, you may want to do a random coin flip if you are in case 2 or 3, because the gray region in case 2 and case 3 has two non-contiguous squares. Alternatively, if you are in case 2 or case 3, you can pick a pont in the "superset" rectangle of case 2 or 3, then reject the point and try again if the point you got is not in one of the two gray squares that are active for that case.
  3 Comments
Daniel Niu
Daniel Niu on 2 Nov 2022
Edited: Daniel Niu on 2 Nov 2022
the grey shadow represent a goal keeper and only the point in the non-grey region, it means the score. it just simulate the penalty kick.
the 5 cases are equally likely options as you assumed.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!