How to plot a regular hexagon using MATLAB?

Asked by Maimouna Louche on 5 Aug 2012
Latest activity Edited by Walter Roberson on 10 Aug 2012

This is what I tried. All I get is a square. I thought the number of x and y gives the figure.

x1=1;y1=-1;x2=-1;y2=1;x3=1;y3=1;x4=-1;y4=-1;x5=1;y5=1;x6=-1;y6=1;
plot(x1,y1,'o',x2,y2,'*',x3,y3,'h',x4,y4,'d',x5,y5,'k',x6,y6,'g')
axis([-2 2 -2 2])

What am I doing wrong? Please help!

Thanks for your time.

1 Comment

Image Analyst on 5 Aug 2012

Points 3 and 5 are the same, and points 2 and 6 are the same, so they'll plot at exactly the same place.

Maimouna Louche

Tags

Products

No products are associated with this question.

2 Answers

Answer by Image Analyst on 5 Aug 2012
Edited by Image Analyst on 5 Aug 2012
Accepted answer

Try this:

theta = 0:60:360;
x = cosd(theta);
y = sind(theta);
plot(x, y, 'b-', 'LineWidth', 3);
axis square;
grid on;
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Plot markers if you want.
plot(x(1),y(1),'o',x(2),y(2),'*',x(3),y(3),'h',...
	x(4),y(4),'d',x(5),y(5),'s',x(6),y(6),'x', ...
	'MarkerFaceColor',[.49 .1 .63], 'MarkerSize', 30) 

2 Comments

Maimouna Louche on 7 Aug 2012

Thanks a lot, Image Analyst. Is that linspace? The way you used theta. I got exacly what I was aiming for.

Thanks for your time.

Image Analyst on 8 Aug 2012

It wasn't linspace(), but you could use linspace() if you wanted to, to get x.

Image Analyst
Answer by Azzi Abdelmalek on 5 Aug 2012
Edited by Azzi Abdelmalek on 5 Aug 2012

% use this function

   function hexagon(cote,x0,y0)
   %cote= side size;,(x0,y0) exagon center coordinates;
   x=cote*[-1 -0.5 0.5 1 0.5 -0.5 -1]+x0
   y=cote*sqrt(3)*[0 -0.5 -0.5 0 0.5 0.5 0]+y0
   plot(x,y,'r','Linewidth',4);grid;
   axis([ x0-cote x0+cote y0-cote y0+cote]);

%example

    hexagon(10,5,8)

1 Comment

Maimouna Louche on 7 Aug 2012

Thank you Azzi Abdelmalek, I finally understood how functon works.

Thanks for your time.

Azzi Abdelmalek

Contact us