Skip to content
Advertisement

Convert phase angle equation from Matlab to Python

I’m trying to adapt code from Matlab to Python. Specifically measuring the phase angle from a group of angles. So using the df below, I have 5 individual labels with an associated angle. I want to measure the phase angle between these points. In Matlab the angle for each Label is passed to the following:

exp(i*ang)

This equals the following:

A_ang = 0.9648 + 0.2632i
B_ang = 0.7452 + 0.6668i
C_ang = 0.9923 + 0.1241i
D_ang = 0.8615 + 0.5077i
E_ang = 0.9943 + 0.1066i

I then divide by the number of angles and pass abs

out = (ac + bc + cc + dc + ec)/5 

total = abs(out)

The final output should be 0.9708

import pandas as pd
import numpy as np

df = pd.DataFrame({                          
    'Label' : ['A','B','C','D','E'],             
    'Angle' : [0.266252,0.729900,0.124355,0.532504,0.106779],           
    })

Advertisement

Answer

Python supports the Complex data type out of the box. And cmath provides access to mathematical functions for complex numbers (Read More). Try the following:

import cmath 

angs = [0.266252,0.729900,0.124355,0.532504,0.106779]

# Create the complex numbers associated with the angles (with r = 1)
nums = [cmath.cos(ang) + cmath.sin(ang) * 1j for ang in angs]

# Compute the total following what you described. 
total = abs(sum(nums))/len(angs)

print (total) #0.9707616522067346
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement