Matlab drives me mad in several ways and even before typing the first line of code, I've been thinking about solving the problems with python.
Let's start.
Problem 1 formulation:
Draw an ellipse with its semi axes measuring a=5 and b=2, then create a script that plots a number n of ellipses equal in size with common center, solve for n=30. Each ellipse should be rotated an angle of pi/n radian from the previous one. The output of the script should look like this:Solution:
##### Libraries #####from numpy import *
from math import *
import pyqtgraph as pg
#####################
##### Input Variables
a=7 # semi axis X value
b=2 # semi axis Y value
n=30 # number of ellipses
#####################
window=pg.plot(title="Concentric Ellipses") #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
E[0,i]=a*cos(alpha[i])
E[1,i]=b*sin(alpha[i])
beta=0 # Ellipse angle variable inicialization
for i in range(n): # Generates n concentric ellipses angled pi/n radians
TM=[[cos(beta),-sin(beta)],[sin(beta),cos(beta)]] # Transformation matrix
RE=dot(TM,E) # RE contains the coordinates of the rotated ellipse
REX=RE[0,:] # RE X values extraction
REY=RE[1,:] # RE Y values extraction
window.plot(REX,REY) # Plots the current rotated ellipse
beta+=pi/n # Increases beta by pi/n steps
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)
The main difference between python and matlab scripts for this exercise is the library import header, being the rest of them very mimetic.
Second exercise on the next post, bye!
No comments:
Post a Comment