How can i create random rectangles (automatically)?
4 views (last 30 days)
Show older comments
I want to create many rectangles. This should be done automatically. How can i do this without typing thousands of values in my code? Is there an solution?
- In my code i wrote every single coordinate point (4 points of each rectangle) manually in my vector "V".
- Also how to connect them. "F"
- And the value of each rectangle. "C"
Thank you for your input/help. I really appreciate it.
clc
clear all
figure;
V = [0,0;1,0;1,1;0,1;5,5;10,5;10,10;5,10;2,2;4,2;4,4;2,4];
F = [1,2,3,4;5,6,7,8;9,10,11,12];%Dieser Vektor sagt mir in welcher Reihenfolge die Punkte
C = [50;24;99];
patch('Faces',F,'Vertices',V,'FaceVertexCData',C,'FaceColor','flat','EdgeColor','none') %Befehl fürs "zeichnen"
colormap(parula)
colorbar
0 Comments
Accepted Answer
Guillaume
on 8 Sep 2016
This will create as many rectangles as you want in any range you want:
numrects = 100; %choose your own value
minx = -10; maxx = 10; %choose your own values
miny = -5; maxy = 8; %choose your own values
rectpos = rand(numrects, 4) .* repmat([maxx - minx, maxy - miny], numrects, 2) + repmat([minx, miny], numrects, 2); %get random corner coordinates
rectpos = [min(rectpos(:, [1, 2]), rectpos(:, [3, 4])), abs(rectpos(:, [3, 4]) - rectpos(:, [1, 2]))]; %transform in [x, y, width, height]
rectcolour = rand(numrects, 3);
figure;
for row = 1:numrects
rectangle('Position', rectpos(row, :), 'EdgeColor', rectcolour(row, :));
end
xlim([minx, maxx]);
ylim([miny, maxy]);
2 Comments
Guillaume
on 8 Sep 2016
Not knowing what your code is, I assume you just need to copy/paste the above, and change the inputs (first three lines) to what you want.
More Answers (2)
Adam
on 8 Sep 2016
Using
doc rectangle
would be simpler than defining a patch like that I would think. Then if you want random positions it is just a case of creating random numbers and because you are defining a top left location and height, width you will always have a rectangle rather than using patch with random numbers.
KSSV
on 8 Sep 2016
clc; clear all
for i = 1:10
ver = RandRect(rand(1,2),rand(1,2)) ;
patch(ver(:,1),ver(:,2),'r')
hold on
end
function vertices = RandRect(P1,P3)
x1 = P1(1) ; y1 = P1(2) ;
x2 = P3(1) ; y2 = P3(2) ;
L = x2-x1 ;
B = y2-y1 ;
P2 = [x1+L y1] ;
P4 = [x1 y1+B] ;
vertices = [P1 ; P2; P3; P4] ;
2 Comments
KSSV
on 8 Sep 2016
Copy the lines:
for i = 1:10
ver = RandRect(rand(1,2),rand(1,2)) ;
patch(ver(:,1),ver(:,2),'r')
hold on
end
where you want to use in your code. and keep the function RandRect.m in the same folder.
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!