How to plot specified semi-circle, rectangle ?
14 views (last 30 days)
Show older comments
Hi all
I have 2 points, and need to plot semi-circle, rectangle as folowing picture.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1227797/image.png)
semi-circle need to perpendiculars with slope of 2 points line.
In Case A - simple case which Ay = By. I created code as:
A = [2,2];
B = [5,2];
plot([A(1) B(1)],[A(2) B(2)],'-og');
hold on;
x_centerCircle = A(1);
y_centerCircle = A(2);
r=1; % Radius 1m
theta = linspace(pi/2, 3*pi/2, 100);
xCirc = r * cos(theta) + x_centerCircle;
yCirc = r * sin(theta) + y_centerCircle;
plot(xCirc, yCirc, 'r');
plot([xCirc(1), xCirc(end)], [yCirc(1), yCirc(end)], 'r');
rectangle('Position',[x_centerCircle x_centerCircle-0.075 5 0.15], 'EdgeColor', 'r');
grid on;
xlim([0 8]);
ylim([0 4]);
But when line AB does not parallel with Ox (Case B), becomes more difficult.
Do anyone show me how to plot for all cases?
Thank you so much
0 Comments
Accepted Answer
Voss
on 12 Dec 2022
Below is a function that does it, and here are some examples of its usage:
create_semi_rect_patch();%[2 2],[5 2],0.15,1)
axis equal
figure();
create_semi_rect_patch([2 2],[2+sqrt(7.56) 3.2],0.15,1);
axis equal
figure();
create_semi_rect_patch([0 2],[0 10],2,1.5);
axis equal
figure();
create_semi_rect_patch([-2 2],[0 0],1,1.5,4);
axis equal
function p = create_semi_rect_patch(A,B,h,r,Npts_semi)
if ~nargin || isempty(A) % if no A specified, use [2 2]
A = [2 2];
end
if nargin < 2 || isempty(B) % if no B specified, use [5 2]
B = [5 2];
end
if nargin < 3 || isempty(h) % if no h specified, use 0.15
h = 0.15; % (half-height of the rectangle)
end
if nargin < 4 || isempty(r) % if no r specified, use 1
r = 1; % (radius of the semi-circle)
end
if nargin < 5 || isempty(Npts_semi) % if no Npts_semi specified, use 100
Npts_semi = 100; % (number of points along semi-circle)
end
% angle from A to B:
theta = atan2(B(2)-A(2),B(1)-A(1));
% coordinates of the corners of the rectangle:
corner_offset = h*[1;-1]*[cos(theta+pi/2) sin(theta+pi/2)];
rect_points = [A+corner_offset; B+corner_offset];
% coordinates of the points along the semi-circle:
theta_semi = linspace(theta+pi/2,theta+3*pi/2,Npts_semi).';
semi_points = A+r*[cos(theta_semi) sin(theta_semi)];
% create the patch:
p = patch( ...
'XData',[semi_points(:,1); rect_points([2 4 3 1],1)], ...
'YData',[semi_points(:,2); rect_points([2 4 3 1],2)], ...
'FaceColor','flat', ...
'EdgeColor','none', ...
'FaceVertexCData',[1 0 0], ...
'FaceAlpha',0.2);
end
More Answers (0)
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!