Plot a rectangular/square box around a set of random points

16 views (last 30 days)
Given a random set of points:
x=rand(1,100)*5;
y=rand(1,100)*5;
scatter(x,y,20,'blue','filled')
xlim([-1 6])
ylim([-1 6])
how can I draw a rectangle that wraps that set of points, and such that the following conditions are fulfilled?
(1) the upper edge and the lower edge of the rectangle are placed at the lowest and highest y-coordinates of the set of points, i.e. at
yl = [min(y) max(y)];
(2) the left and the right edges are placed at the leftmost and rightmost x-coordinates of the set of points, i.e.
xl = [min(x) max(x)];
Visually, my desired output would be the following one:

Accepted Answer

Mann Baidi
Mann Baidi on 10 Jun 2024
Edited: Mann Baidi on 10 Jun 2024
Hi,
You can plot lines around the random points that will wrap all the points using the following line of code:
% Generate random points
numPoints = 50; % Number of random points
x = rand(1, numPoints) * 10; % Random x coordinates between 0 and 10
y = rand(1, numPoints) * 10; % Random y coordinates between 0 and 10
% Determine the min and max coordinates
xmin = min(x);
xmax = max(x);
ymin = min(y);
ymax = max(y);
% Create coordinates for the rectangular box
box_x = [xmin, xmax, xmax, xmin, xmin];
box_y = [ymin, ymin, ymax, ymax, ymin];
% Plot the points
figure;
scatter(x, y, 'filled');
hold on;
% Plot the rectangular box
plot(box_x, box_y, 'r-', 'LineWidth', 2);

More Answers (0)

Categories

Find more on Two y-axis 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!