Matlab to Python

Last edited: February 25th, 2017

A brief how-to on similarities and differences between the two languages.


This how-to will walk you through some of the similarities and most encountered differences between the Matlab and Python programming languages. This will be done by considering a quite simple computational physics example, calculating the trajectory of a ball being thrown into the wind.

Matlab

We set constant values:

v0 = 10;        % Start velocity
theta0 = 45;    % Throw angle
g = 9.81;       % Gravity
m = 0.1;        % Mass of the ball
rad = 0.05;     % Radius of the ball
cd = 0.47;      % Drag coefficient
rho = 1.15;     % Air density in kg/m^3
t_max = 3;      % Maximum simulation time
dt = 0.001;     % Time step

We see that every statement in Matlab has to be followed by a semi-colon, ;. This prevents the value of the assignment to be printed to screen.

Below we notice another difference between Matlab and Python: While Matlab uses the more familiar ^ to set the exponent of a number, Python uses **.

area = pi*rad^2;            % Projected area of the ball
k = rho*cd*area/(2*m);      % Air drag
n_max = floor(t_max/dt);    % Number of time steps

We now initialize the solution arrays with zeros. We want a one-dimensional array of length n_max, and hence use (n_max, 1) as the function argument.

x = zeros(n_max,1);
u = zeros(n_max,1);
y = zeros(n_max,1);
w = zeros(n_max,1);

In the following code, we set the initial values of the solution arrays.

theta0 = theta0*pi/180; % Convert throwing angle to radians
x(1) = 0;               % Define starting position, x direction
y(1) = 0;               % Define starting position, y direction
u(1) = v0*cos(theta0);  % Initial velocity in x-direction
w(1) = v0*sin(theta0);  % Initial velocity in y-direction

We see that Matlab uses () to access an element of an array, and the index 1 accesses the first element of the array. The last element can be accessed by using using the index end. A range of values can be accessed by using start:step:stop, where start denotes the first index, step the step between indexes, and stop the last index to be included.

We now use Euler's method to solve the equations of motion in time. This can be done using a for-loop. In Matlab a for-loop is started using for and setting a counter equal to the array that is to be iterated over. The loop has to be ended with an end statement. Matlab will not care about indentation inside the loop, but treats everything between for and end as inside the loop. However, indentation helps keeping the code readable.

for n = 1:(n_max-1)
    drag = k*dt*sqrt((u(n)-windX)^2 + w(n)^2);
    x(n+1) = x(n) + dt*u(n);
    u(n+1) = u(n) - drag*(u(n)-windX);
    y(n+1) = y(n) + dt*w(n);
    w(n+1) = w(n) - g*dt - drag*w(n);
    % Check if the ball is below the ground
    if y(n+1) <= 0
        x = x(0:n+2);
        y = y(0:n+2);
        break
    end
end

Now that we have calculated the trajectory of the ball, we want to plot it. In Matlab the plot functions are build in.

We create a new figure for our plot using figure(), and plot a simple line plot using plot(x,y), where x is the array of values for the x-coordinate, and y is the array of values for the y-coordinate.

figure()
plot(x,y)

In order to be able to reuse the above code in a simple way, it can be convenient to define a function which simulates the throw based on various input parameters like for instance the initial velocity and throw angle. In Matlab a function is defined using function, and is ended using end. Everything between these two statements will be treated as inside the function. As a short example consider the following:

function [output1, output2] = function_name(input1, input2)
    output1 = input1^2;
    output2 = input1*input2;
end

A call to the above function is then done using

[output1, output2] = function_name(input1, input2);

Python

We set constant values:

v0 = 10     # Start velocity
theta0 = 45 # Throw angle
g = 9.81    # Gravity
m = 0.1     # Mass of the ball
rad = 0.05  # Radius of the ball
cd = 0.47   # Drag coefficient
rho = 1.15  # Air density in kg/m^3
t_max = 3   # Maximum simulation time
dt = 0.001  # Time step

We also notice that while a % begins a comment in Matlab, the same is done by using # in Python.

We will now need the number pi, which unlike in Matlab, is not built-in in Python. Hence we have to add the line:

from numpy import *

What the above line does, is import the numpy library, which holds a lot of useful functions. The fact that we import * just means that we import every function in numpy. We will try to point out the numpy functions used along the way.

area = pi*rad**2        # Projected area of the ball
k = rho*cd*area/(2*m)   # Air drag
n_max = floor(t_max/dt) # Number of time steps

Below we use another numpy function, zeros. Notice that unlike in Matlab, you can give only the length of array.

x = zeros(n_max)
u = zeros(n_max)
y = zeros(n_max)
w = zeros(n_max)

Below cos() and sin() are functions from the numpy library.

theta0 = theta0*pi/180  # Convert throwing angle to radians
x[0] = 0                # Define starting position, x direction
y[0] = 0                # Define starting position, y direction
u[0] = v0*cos(theta0)   # Initial velocity in x-direction
w[0] = v0*sin(theta0)   # Initial velocity in y-direction

However, Python uses [] to access an element of an array, and the index 0 accesses the first element of the array! Backwards indexing is also possible, where the last element can be accessed by using using the index -1. A range of values can be accessed by using start:stop:step, where start denotes the first index, step the step between indexes, and stop the last index to be included. However, if you use choose stop=-1, the last element of the array will not be included. Notice also that the ordering differs between Matlab and Python!

A for-loop in python is also started using for, and the counter set to be in the iteration array. The colon : signifies the start of the loop. However, there is no end statement in Python: Python treats everything that is indented following the : as part of the loop, and ends at the next unindented code block. Hence we have to be very careful to ensure correct indentation of the code! Below we use the function sqrt() from numpy.

for n in range(n_max-1):
    drag = k*dt*sqrt((u[n]-windX)**2 + w[n]**2)
    x[n+1] = x[n] + dt*u[n]
    u[n+1] = u[n] - drag*(u[n]-windX)
    y[n+1] = y[n] + dt*w[n]
    w[n+1] = w[n] - g*dt - drag*w[n]
    # Check if the ball is below the ground
    if y[n+1] <= 0:
        x = x[0:n+2]
        y = y[0:n+2]
        break

In Python however, we have to import a library to be able to plot. We will here use the pyplot in the matplotlib library, which to a large extent uses the same plotting commands as Matlab.

from matplotlib.pyplot import *

In addition to the functions used in Matlab, we have to make a call to show() in order for Python to display the figure. Alternatively, the figure can be saved to file, or in IPython Notebook shown inline if %matplotlib inline is added to the file.

figure()
plot(x,y)
show()

In Python a function is defined using def followed by the function name and input variables, and a colon. Again the indentation following the colon is important: Every line of code which is indented compared to the def statement included in the function, until the first non-indented line. In addition, the function output is defined using the return statement. In Python we then get the following:

def function_name(input1, input2):
    output1 = input1**2
    output2 = input1*input2
    return output1, output2

A call to the above function is then done using

output1, output2 = function_name(input1, input2)

The above example illustrates some, but far from all, differences between the Matlab and Python programming languages. However, it will hopefully be enough to simplify switching between the two languages. For further details, we would recommend studying the documentation. And as always: someone else has definitely had the same questions as you have - a quick search on the internet will most certainly give answers.