Sunday, 5 January 2014

Typical degree problem & Python: Part 2

Problem 2 formulation:

Create a script that plots an n vertexes polygon inscribed in an ellipse with semi axis a=7, b=2. Solve for n=12


Solution:

##### Libraries #####

from numpy import *


import pyqtgraph as pg


#####################


a=7 # Semi axis X value


b=2 # Semi axis Y value 


n=12 # Polygon vertex number


window=pg.plot(title="Inscribed Polygon") #Creates plot window called window


alpha=linspace(0,2*pi) # Creates line matrix with values from 0 to 2*pi


SA=size(alpha) # Gets the size of alpha matrix


E=zeros([2,SA]) # Creates a 2xSA matrix filled with zeros


for i in range(SA): # Gets X,Y values of the ellipse and stores them in E[0,i]

  E[0,i]=a*cos(alpha[i])
  E[1,i]=b*sin(alpha[i])

window.plot(E[0,:],E[1,:]) # Plots the ellipse


V=zeros([2,n+1]) # Array filled with zeros that will contain polygon vertexes

alpha=0 # Variable reset

for i in range (n+1): # Bucle that obtains the coordinates of an n vertexes polygon

  V[0,i]=cos(alpha)
  V[1,i]=sin(alpha)
  alpha+=2*pi/n

VSM=[[a,0],[0,b]] # Transformation matrix that will inscribe the polygon inside the ellipse


V=dot(VSM,V) # Transformation matrix * Polygon


window.plot(V[0,:],V[1,:]) # Plots the polygon





To see it working, open a terminal (ctrl+alt+t), type "python" and then copy-paste the code.(you need to have installed the pyqtgraph module in order to plot, see this post)

This problem is very similar to the Problem 1 and without the importing part it is almost equal to the matlab script.


Next post will be about mirroring an image with a line equation as a mirror line. 

Stay tuned, bye!