matlab_to_python
matlab_to_python
1 Introduction
Converting MATLAB code to Python is a common task in control systems,
especially for system analysis, controllability, observability, PID controller de-
sign, state estimation, and noise filtering. This report describes the conversion
process and the equivalent Python libraries for MATLAB functions.
3 Conversion Process
3.1 Equivalent Python Libraries
• NumPy: For numerical computations and matrix manipulation.
• SciPy: For scientific functions, especially scipy.signal for dynamic sys-
tems.
• Control Systems Library (python-control): For system analysis and
controller design.
1
• Matplotlib: For visualization.
• Scipy.Signal: For filtering and noise addition.
Python :
1 import numpy as np
2 import matplotlib . pyplot as plt
3 import control as ct
4
5 # Define the transfer function
6 sys = ct . T r a n s f e r Fu n c t i o n ([1] , [1 , 2 , 1])
7
8 # Time response
9 t , y = ct . step_response ( sys )
10 plt . plot (t , y )
11 plt . title ( ’ Step Response ’)
12 plt . xlabel ( ’ Time ’)
13 plt . ylabel ( ’ Amplitude ’)
14 plt . show ()
Python :
1 import control as ct
2
3 # Define state - space matrices
4 A = np . array ([[1 , 1] , [0 , 1]])
5 B = np . array ([[1] , [0]])
6 C = np . array ([[1 , 0]])
7 D = np . array ([[0]])
8
9 # Create the system
10 sys = ct . StateSpace (A , B , C , D )
11
12 # C on tr o ll ab i li ty
2
13 Co = ct . ctrb (A , B )
14
15 # Observability
16 Ob = ct . obsv (A , C )
Python :
1 # Define PID gains
2 Kp = 1
3 Ki = 1
4 Kd = 1
5
6 # Create PID controller
7 C = ct . T r a n s f e r F u n c t io n ([ Kd , Kp , Ki ] , [1 , 0])
8
9 # Closed - loop system
10 sys_cl = ct . feedback ( C * sys , 1)
11
12 # Time response
13 t , y = ct . step_response ( sys_cl )
14 plt . plot (t , y )
15 plt . title ( ’ Closed - Loop Step Response ’)
16 plt . xlabel ( ’ Time ’)
17 plt . ylabel ( ’ Amplitude ’)
18 plt . show ()
Python :
1 # State feedback
2 K = ct . place (A , B , [ -2 , -3])
3
4 # State estimation ( observer )
5 L = ct . place ( A .T , C .T , [ -4 , -5]) . T
6
3
7 # Create observer
8 obs = ct . StateSpace ( A - L @ C , B , C , D )
9
10 # Simulate observer
11 t , y = ct . step_response ( obs )
12 plt . plot (t , y )
13 plt . title ( ’ Observer Response ’)
14 plt . xlabel ( ’ Time ’)
15 plt . ylabel ( ’ Amplitude ’)
16 plt . show ()
Python :
1 import numpy as np
2 import matplotlib . pyplot as plt
3 from scipy . signal import butter , filtfilt
4
5 # Add noise to a signal
6 t = np . arange (0 , 10 , 0.01)
7 y = np . sin ( t )
8 noise = 0.1 * np . random . randn ( len ( t ) )
9 y_noisy = y + noise
10
11 # Design a low - pass filter
12 fc = 1 # Cutoff frequency
13 fs = 100 # Sampling frequency
14 b , a = butter (2 , fc / ( fs / 2) , btype = ’ low ’)
15
16 # Apply the filter
17 y_filtered = filtfilt (b , a , y_noisy )
18
19 # Plot results
20 plt . figure ()
21 plt . plot (t , y_noisy , label = ’ Noisy Signal ’)
22 plt . plot (t , y_filtered , label = ’ Filtered Signal ’)
23 plt . legend ()
24 plt . title ( ’ Noise Filtering ’)
25 plt . xlabel ( ’ Time ’)
26 plt . ylabel ( ’ Amplitude ’)
27 plt . show ()
4
4 Controllability and State Estimation
4.1 Controllability
Controllability is a property of a system that determines whether it is possible
to steer the system from any initial state to any desired state in finite time using
appropriate control inputs. For a linear time-invariant (LTI) system described
by:
ẋ(t) = Ax(t) + Bu(t)
where:
• x(t) is the state vector,
• u(t) is the control input vector,
• A is the state matrix,
• B is the input matrix.
The system is controllable if the controllability matrix C has full rank:
C = [B AB A2 B ... An−1 B]
1 A = [1 1; 0 1];
2 B = [1; 0];
3 C = [1 0];
4 D = 0;
5
6 % Create state - space system
7 sys = ss (A , B , C , D ) ;
8
9 % Compute c on t ro ll ab i li ty matrix
10 Co = ctrb ( sys ) ;
11
12 % Check rank
13 rank ( Co )
1 import numpy as np
2 import control as ct
3
4 # Define state - space matrices
5 A = np . array ([[1 , 1] , [0 , 1]])
6 B = np . array ([[1] , [0]])
7
8 # Compute c on t ro ll ab i li ty matrix
9 Co = ct . ctrb (A , B )
5
10
11 # Check rank
12 print ( " Rank of co n tr ol lab il it y matrix : " , np . linalg . matrix_rank ( Co ) )
y(t) = Cx(t)
the observer dynamics are given by:
˙
x̂(t) = Ax̂(t) + Bu(t) + L(y(t) − C x̂(t))
where:
• x̂(t) is the estimated state vector,
• L is the observer gain matrix.
The observer gain L is designed such that the eigenvalues of (A − LC) are
placed in desired locations for stable and fast estimation.
1 import numpy as np
2 import control as ct
3
4 # Define state - space matrices
5 A = np . array ([[1 , 1] , [0 , 1]])
6 B = np . array ([[1] , [0]])
6
7 C = np . array ([[1 , 0]])
8 D = np . array ([[0]])
9
10 # Desired observer poles
11 obs_poles = [ -4 , -5]
12
13 # Compute observer gain
14 L = ct . place ( A .T , C .T , obs_poles ) . T
15
16 # Create observer system
17 obs = ct . StateSpace ( A - L @ C , B , C , D )
18
19 # Simulate observer response
20 t , y = ct . step_response ( obs )
21 plt . plot (t , y )
22 plt . title ( ’ Observer Response ’)
23 plt . xlabel ( ’ Time ’)
24 plt . ylabel ( ’ Amplitude ’)
25 plt . show ()
u(t) = −Kx(t)
where K is the feedback gain matrix. The closed-loop system dynamics become:
ẋ(t) = (A − BK)x(t)
7
1 # Define state - space matrices
2 A = np . array ([[1 , 1] , [0 , 1]])
3 B = np . array ([[1] , [0]])
4
5 # Desired closed - loop poles
6 desired_poles = [ -2 , -3]
7
8 # Compute feedback gain
9 K = ct . place (A , B , desired_poles )
10
11 # Closed - loop system
12 A_cl = A - B @ K
13 sys_cl = ct . StateSpace ( A_cl , B , C , D )
5 Bibliography
• NumPy: https://numpy.org/
• SciPy: https://www.scipy.org/
6 Conclusion
The conversion of MATLAB code to Python is facilitated by specialized libraries
such as numpy, scipy, control, and matplotlib. These tools allow reproduc-
ing MATLAB functionalities while leveraging Python’s flexibility and power.
This report covers essential aspects of system analysis, controller design, state
estimation, and noise filtering.