how to generate random number in a rectangle like this?
1 次查看(过去 30 天)
显示 更早的评论
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1178013/image.png)
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 个评论
William Rose
2022-11-3
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)
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.
采纳的回答
William Rose
2022-11-2
@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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Labels and Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!