MATLAB Function Generates the Vertices of a Regular N-gon with Line Segments

조회 수: 8 (최근 30일)
Sophie Culhane
Sophie Culhane 2020년 12월 3일
답변: Steven Lord 2020년 12월 4일
My task is to write a MATLAB function that generates the verticies of a regular n-gon and draws a line segment between each pair of verticies. The routine is only to plot one line segment at a time and the graph can only be generated by one "plot" command. I have a very rough outline of a program written up. There are some issues with the program. It plots one less vertice than n and I have no line segments connecting every vertice. Please help me to figure out where to go next with my program.
function e3(n)
%
%
t = linspace(0,1,n);
x = cos(t.*2*pi);
y = sin(t.*2*pi);
plot(x,y)
axis off
axis equal

답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 12월 3일
편집: Ameer Hamza 2020년 12월 3일
You need n+1 points, because points at angle of 0 and 2*pi are same.
t = linspace(0,1,n+1);
Can you explain, what do you mean by connecting all the vertices?
  댓글 수: 7
Ameer Hamza
Ameer Hamza 2020년 12월 3일
Try this
n = 15;
t = linspace(0,1,n+1);
x = cos(t.*2*pi);
y = sin(t.*2*pi);
[m1, m2] = ndgrid(1:n);
combs = unique(sort([m1(:) m2(:)],2), 'rows');
combs(diff(combs,[], 2)==0, :) = [];
hold on
for i = 1:size(combs,1)
plot(x(combs(i,:)), y(combs(i,:)), 'b')
end
axis off
axis equal
Sophie Culhane
Sophie Culhane 2020년 12월 4일
I am not able to use commands "hold on", "ndgrid", "sort", or "diff" as we have not learned those yet. Is there another way to go about this problem without those commands?

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2020년 12월 4일
You might find the degree-based trig functions sind and cosd useful. If you need to work exclusively with radians, the sinpi and cospi functions may be useful as well.
Finally for your iterative plotting either the comet or animatedline and addpoints functions may be of use.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by