Random squares/rectangles in a square
Afficher commentaires plus anciens
I have a square of size 1, that is (0,1)x(0,1). In this square, I would like to create random squares or rectangles of various sizes where none of them share an edge with each other. Meaning, I want them randomly spaced out. Then, i would like to save the values or coordinates within each squares to compare them with an input (x,y) such that (x,y) has value 1 if it's in the square, and zero if it's not.
I want to repeat this(random sampling of squares) for 5 different samples.
Thanks!
Réponse acceptée
Plus de réponses (1)
Do you want
A. One random square inside the unit square, and you want choose that random square 5 times, and each time you want to see if a random point (x,y) falls within the random square?
or
B. Five "random" non-overlapping little squares inside the unit square. If this is the case, then the 5 little squares are not really random, since the location and size of each is constrained by the square(s) already chosen.
or something else? I assume you want A. I will do A, with six examples, instead of five. I will use one random point and compare it to six different squares.
x=rand(1,1); y=rand(1,1); % point of reference
pointInSquare=zeros(1,6); % initialize array for whether point is in the square
figure
for i=0:1
for j=0:2
BL=rand(1,2); %x,y coords of bottom left corner of random square inside the unit square
s=(1-max(BL))*rand(1,1); % side length
P=[BL; BL+[0,s]; BL+[s,s]; BL+[s,0]]; % array of vertices of square
pgon=polyshape(P); % create square polygon
pointInSquare(3*i+j+1)=inpolygon(x,y,P(:,1),P(:,2)); % =1 if x,y in or on square
subplot(2,3,3*i+j+1);
plot(pgon); hold on; plot(x,y,'r*'); axis equal; xlim([0,1]); ylim([0,1])
end
end
fprintf('(x,y) in square for %d square(s).\n',sum(pointInSquare));
Try it.
1 commentaire
Tony Haines
le 24 Mai 2024
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


