Python

From ComputingForScientists

Jump to: navigation, search

Contents

  1. Python for MATLAB users
  2. Installing Python
    1. Linux
    2. Windows
  3. Documentation
  4. Printing Values
    1. Problems
  5. Data Types
    1. Problems
  6. Creating and Iterating over Arrays
    1. Problems
  7. Creating and Iterating over Matrices
    1. Problems
  8. Populating Arrays
    1. Problems
  9. Populating Matrices
    1. Problems

1. Python for MATLAB users

This tutorial covers elementary Python 2.7 programs and compares them with equivalent MATLAB programs. An excellent free reference for Python 2.7 is http://greenteapress.com/wp/think-python/.

For scientific computing, one will typically also use the following Python packages that are not a core part of Python:

  • Scipy (Scientific Python) for matrix manipulation
  • Numpy (Numerical Python) for numerical algorithms
  • Matplotlib for plotting

However, this tutorial only covers Python 2.7. Once you are familiar with the basics of Python syntax, you are encouraged to start to use these packages.

Note that when searching on the web for help on Python, it is important to include "Python 2" or "Python 2.7". Python 3 is a very different version of Python, and the community has been slow to adopt it [1] [2].

References

2. Installing Python

Prior to starting this tutorial, install Anaconda [3]. Anaconda includes Python 2.7 and a number of IDEs (Integrated Development Environments) and tools and packages for developing scientific software with Python. I recommend the Spyder IDE for this tutorial.

2.1. Linux

Download and install

cd ~/Downloads; curl -O http://repo.continuum.io/archive/Anaconda2-4.0.0-Linux-x86_64.sh
cd ~/Downloads; bash Anaconda2-4.0.0-Linux-x86_64.sh
cd ~/Downloads; rm Anaconda2-4.0.0-Linux-x86_64.sh

Start Spyder

~/anaconda2/bin/spyder

2.2. Windows

Download the package at https://www.continuum.io/downloads and then search for the program named Spyder.

3. Documentation

Python 2.7

help("print")
# or
help('print')

MATLAB

help disp
% or
% help('disp')

Note that in MATLAB, print has a different meaning than in Python. In MATLAB, print is used to save an image of a plot. In Python, print is used to display the value of a variable. Also, in MATLAB, only 's are used.

4. Printing Values

Python 2.7

a = 1.0
print("a = %4.2f" % a)
# or
# print a
# or
# print(a)
b = 1.0
print("a = %4.2f, b = %4.2f" % (a,b))

Note the meaning of the second % is different than that of the first. I am not sure why a comma was not used; % has enough meanings already.

MATLAB

a = 1.0;
fprintf("a = %4.2f",a);
% or
% a
% or
% disp(a)
b = 1.0;
fprintf("a = %4.2f, b = %4.2f",a,b);

4.1. Problems

Write MATLAB and Python programs that display exactly the following when executed.

4.1.1.

a = 1
b = 2
c = 3

4.1.2.

a = 1.00
b = 2.00
c = 3.00

4.1.3.

a = 1, b = 2, c = 3

4.1.4.

a = 1.000, b = 2.000, c = 3.000

5. Data Types

In MATLAB, when you enter a=1, a is assigned the floating point value of 1. In Python, when you type a=1, a is assigned the integer value of 1. To see the difference, consider

Python 2.7

a = 1
print(a/2)   # displays 0
print(a*0.5) # displays 0.5
 
a = 1.
print(a/2)  # displays 0.5
print(a/2.) # displays 0.5
 
b = 3
print(b/2)  # displays 1
print(b/2.) # displays 1.5

In the above, a trailing . tells the Python interpreter that the variable is to be a floating point number. The important thing to remember is that, most often, when dividing an integer by an integer, the result is the same as the result of division with the fraction removed. There are many other considerations that are not covered in this tutorial.

MATLAB

a = 1
a/2   % displays 0.5000
a*0.5 % displays 0.5000
 
a = 1.
a/2  % displays 0.5000
a/2. % displays 0.5000
 
b = 3
b/2  % displays 1.5000
b/2. % displays 1.5000

5.1. Problems

5.1.1.

What will be displayed when the following commands are executed in Python?

print(4/3)
print(4/3.)
print(4./3)

What will be displayed when the following commands are executed in MATLAB?

4/4
4/3.
4./3

5.1.2.

Write a program in MATLAB and Python that computes the two solutions to x2 + x - 1 = 0 and then prints them in the following format

x1 = ?.???
x2 = ?.???

When executed, your the ?s should be replaced with the correct values.

Start your program with

import math

so that square roots can be computed using math.sqrt, e.g.,

import math
math.sqrt(2)

6. Creating and Iterating over Arrays

  • MATLAB uses zero-based indexing, so the first element of array a is a[0].
  • MATLAB uses one-based indexing, so the first element of array a is a(1).

Note also that Python uses square braces where MATLAB uses parentheses.

Python 2.7

a = [1.,2.,3.]
for i in range(len(a)):
    print "a[%d] = %f" % (i, a[i])

Note the missing end statement. Python uses indentation to determine where the end should be placed. Also note the easy-to-forget : at the end of the for statement.

See help("range") and help("len"). Note that it is better to use xrange instead of range [4].

MATLAB

a = [1,2,3];
for i = 1:length(a)
    fprintf('a(%d) = %f\n',i,a(i));
end

6.1. Problems

Create an array with the 11 values of 10,9,8, ..., 0 in Python and MATLAB. When executed, the Python program should display

a[0] = 10
a[1] = 9
...
a[10] = 0

and the MATLAB program should display

a(1) = 10
a(2) = 9
...
a(11) = 0

7. Creating and Iterating over Matrices

Python 2.7

A = [[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]
for i in range(len(A)):
    for j in range(len(A[i])):
        print "A[%d][%d] = %f" % (i, j, A[i][j])

A is called a list (which has elements of lists). A is not really a matrix but was only made to look like one in this example. This is allowed: A = [[1.,2.,3.,4.,5.],[4.,5.,6.],[7.,8.,9.]]; len(A[i]) means the number of elements in the ith list of A.

MATLAB

A = [1,2,3 ; 4,5,6 ; 7,8,9];
for i = 1:size(A,1)
    for j = 1:size(A,2) % or length(A(i,:))
        fprintf('A(%d,%d) = %f\n',i,j,A(i,j))
    end
end

In the MATLAB example, the number of columns in each row does not change, so we use size(A,2). To make it look more like the Python example, we can use length(A(i,:)), which is the number of columns in row i.

7.1. Problems

7.1.1.

Create and display a matrix with the diagonal elements having the value of 1 in both Python and MATLAB. All non-diagonal elements should be zero.

8. Populating Arrays

Python 2.7

a = []
for i in range(10):
    print "a[%d] = %f" % (i, a[i])
    a.append(i/10.)

8.1. Problems

8.1.1.

Write a MATLAB program that produces the same output as the given Python program.

9. Populating Matrices

Python 2.7

A = []
for i in range(3):
    A.append([])
    for j in range(3):
        A[i].append(float(i)/10)
        print "A[%d][%d] = %f" % (i, j, A[i][j])

9.1. Problems

9.1.1.

Write a MATLAB program that produces the same output as the given Python program.

9.1.2.

Write MATLAB and Python programs that create a 5x5 matrix of all zeros except that the elements in the first and last columns have values of 1. Do this without using an if statement (use multiple loops).

9.1.3.

Write MATLAB and Python programs that create a 5x5 matrix of all zeros except that the diagonal elements have a value of 1. Do this without using an if statement (use multiple loops).

Personal tools