# How to draw rectangle with coordinate, height and width provided?

92 views (last 30 days)
Atanu on 20 Aug 2022
Answered: Simon Chan on 21 Aug 2022
How do I draw red rentangles as shown the image if the black and green coordinates are provided?
The width and height is same for all the rectangles and they are also provided. I am familiar with the following.
rectangle('Position', [xLeft, yBottom, width, height])
This only works for upper right green coordinate, does not resolve the other 3 green points.

Steven Lord on 20 Aug 2022
You could call the patch function, or if you need to draw a large collection of rectangles you could create one polyshape then use the rotate, scale, and translate functions to make copies of that initial object in different locations and orientations.

Simon Chan on 21 Aug 2022
Another option is to determine the coordinates of the lower left corner of the rectangle before you draw it. It can be determined by selecting the smallest value from the given two points.
The following shows an example of drawing the lower right rectangle in your figure:
green_dot = [-6 4]; % Coordinates of the green dot (Given in x,y order)
black_dot = [-1 1]; % Coordinates of the black dot (Given in x,y order)
width = 5; % Width of a rectangle (Given)
height = 3; % Height of a rectangle (Given)
%
combine = [green_dot;black_dot]; % Combine the coordinates vertically
f = figure;
ax = gca;
plot(combine(1,1),combine(1,2),'g*'); % Only for illustration, plot the green dot
hold(ax,'on');
plot(combine(2,1),combine(2,2),'k*'); % Only for illustration, plot the black dot
rectangle(ax,'Position', [min(combine(:,1)), min(combine(:,2)), width, height]); % Draw the rectangle
xline(ax,0,'--'); % For illustration only
yline(ax,0,'--'); % For illustration only
hold(ax,'off');
set(ax,'XLim',[-10 10],'YLim',[-10 10]); % Set the limits
On the other hand, you may also draw the rectangle without using the given width and height since the two diagonal coordinates already defines the size of the rectangle. You may refer to the following:
rectangle(ax,'Position', [min(combine(:,1)), min(combine(:,2)), abs(diff(combine(:,1))), abs(diff(combine(:,2)))]);

### Categories

Find more on Surface and Mesh Plots in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by