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

94 ビュー (過去 30 日間)
Atanu
Atanu 2022 年 8 月 20 日
回答済み: Simon Chan 2022 年 8 月 21 日
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.

回答 (2 件)

Steven Lord
Steven Lord 2022 年 8 月 20 日
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
Simon Chan 2022 年 8 月 21 日
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)))]);

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by