Lecture for the course Python for MATLAB users, by Olivier Verdier

We begin by importing scientific packages in the global namespace:

In [2]:
%pylab
Using matplotlib backend: MacOSX
Populating the interactive namespace from numpy and matplotlib

We tell matplotlib to plot inside this notebook.

In [3]:
%matplotlib inline

Notebook

Shift+enter, help, save, %whos, %pylab, %debug, text+Python, up-downloadable, Python notebook for matlab users, Nature article, nonlinear evaluation

In [4]:
a = 3
b = 10

Basic types

  • Integers
  • Floats
  • Complex (conjugate, real(), imag(), .real, .imag)

Operations (*,+,-,**,/), and //. Operations %, int?

In [5]:
i = 3
In [8]:
print(i)
3
In [7]:
i
Out[7]:
3
In [9]:
Out[7] + 10
Out[9]:
13
In [10]:
type(i)
Out[10]:
int
In [14]:
%whos
Variable   Type    Data/Info
----------------------------
a          int     3
b          int     10
i          int     3
In [15]:
f = 2.3
In [16]:
type(f)
Out[16]:
float
In [17]:
f + i
Out[17]:
5.3
In [18]:
print(type(1))
print(type(1.))
<class 'int'>
<class 'float'>
In [19]:
z = 1. + 2.j
In [20]:
print(z)
(1+2j)
In [21]:
J = 1.j
In [22]:
2 + 3*J
Out[22]:
(2+3j)
In [24]:
type(2+3j)
Out[24]:
complex
In [25]:
z
Out[25]:
(1+2j)
In [27]:
z.real
Out[27]:
1.0
In [28]:
z.imag
Out[28]:
2.0
In [30]:
z.conjugate()
Out[30]:
(1-2j)
In [31]:
%whos
Variable   Type       Data/Info
-------------------------------
J          complex    1j
a          int        3
b          int        10
f          float      2.3
i          int        3
z          complex    (1+2j)
In [32]:
f * i
Out[32]:
6.8999999999999995
In [33]:
f + i
Out[33]:
5.3
In [34]:
2^3
Out[34]:
1
In [35]:
2**3
Out[35]:
8
In [36]:
2/3
Out[36]:
0.6666666666666666
In [37]:
2//3
Out[37]:
0
In [38]:
10//4
Out[38]:
2
In [42]:
print(10.1//4.1)
print(floor(10.1/4.1))
2.0
2.0
In [43]:
# comment
In [44]:
pi
Out[44]:
3.141592653589793

Strings

Double, single quotes, triple, escape (\), concatenation (+), interpolation (%, format)

In [49]:
s = "hello " 
In [50]:
me = "Olivier"
In [51]:
s + me
Out[51]:
'hello Olivier'
In [60]:
template = "Hello {}, my name is {}"
In [61]:
template.format("Olivier", "Jupyter")
Out[61]:
'Hello Olivier, my name is Jupyter'
In [54]:
template.format("Åsa")
Out[54]:
'Hello Åsa'
In [55]:
s_ = 'single quotes instead'
In [56]:
s__ = "I'm happy"
In [58]:
print(s)
print(s__)
hello 
I'm happy
In [ ]:
s = """Three quotes
with return inside
another one
"""
In [63]:
s = "hello, \nI'm happy"
print(s)
hello, 
I'm happy

Functions

def, name, parameters, colon :, indentation block, return, execution with (), pass function around

In [67]:
def my_function(param):
    print(param)
    return 3
In [68]:
a = my_function("argument")
argument
In [69]:
a
Out[69]:
3
In [78]:
def add_prod(x1, x2):
    """This is a nice function,
    which computes add and product of
    two numbers"""
    return x1 + x2, x1*x2
In [79]:
add_prod?
In [74]:
r = add_prod(2,3)
In [75]:
print(r)
(5, 6)
In [76]:
r[0]
Out[76]:
5
In [77]:
r[1]
Out[77]:
6
In [73]:
print(s,p)
5 6
In [104]:
def greetings(name):
    template = "Hello {}, how are you??"
    print(template)
    print("still in function")
    

print("I'm outside the function")
I'm outside the function
In [86]:
greetings(3)
Out[86]:
'Hello 3, how are you??'
In [88]:
def print_greetings():
    print("Hi!")
In [96]:
def compute():
    x = 2 + 5
    return x
In [97]:
def post_process(x):
    return x + 10
In [98]:
post_process(compute())
Out[98]:
17
In [99]:
x = print_greetings
In [100]:
print(x)
<function print_greetings at 0x1072856a8>
In [101]:
x()
Hi!
In [89]:
print_greetings() # function execution
Hi!
In [90]:
print_greetings # just the function
Out[90]:
<function __main__.print_greetings>
In [102]:
def execute(f):
    f()
In [103]:
execute(print_greetings)
Hi!
In [ ]:
x = print_greetings
In [ ]:
x()
In [ ]:
def get_number():
    return 2.
In [ ]:
y = get_number
y + 2
In [ ]:
"2" + 3
In [ ]:
2. + 3
In [ ]:
x = 2.
In [ ]:
x.__add__(3)

If Statements

step function (plot+vectorize?), comparison ops ==, !=, <, >, <=, >=. Logical ops not, and, or, bool

In [108]:
def sign(x):
    if x > 0:
        # several instructions here
        return 1.
    elif x > -1:
        return 0.
    else:
        return -1
In [110]:
def inside(x):
    if (x < 0) and (x > -1):
        return "fantastic"
    else:
        return "too bad"
In [112]:
inside(-.5)
Out[112]:
'fantastic'
In [113]:
2 > 3 or 10 > 5
Out[113]:
True
In [114]:
not 3 < 5
Out[114]:
False
In [109]:
sign(-.5)
Out[109]:
0.0
In [106]:
sign(3)
Out[106]:
1.0
In [107]:
sign(-1)
Out[107]:
-1.0

Lists

[], accessing (from zero!), altering, append, len, concatenate +, and *, slicing :, last element -1

In [115]:
L = [2, 3, 4]
In [116]:
L[0]
Out[116]:
2
In [117]:
L[1]
Out[117]:
3
In [118]:
len(L)
Out[118]:
3
In [119]:
L.append(10)
print(L)
[2, 3, 4, 10]
In [120]:
L.append("hello")
print(L)
[2, 3, 4, 10, 'hello']
In [121]:
L[4] = 11
print(L)
[2, 3, 4, 10, 11]
In [122]:
L[-1]
Out[122]:
11
In [123]:
L[-2]
Out[123]:
10
In [124]:
L[-0]
Out[124]:
2
In [125]:
L
Out[125]:
[2, 3, 4, 10, 11]
In [126]:
L[1:4]
Out[126]:
[3, 4, 10]
In [127]:
L[1:-1]
Out[127]:
[3, 4, 10]
In [128]:
L[2:-1]
Out[128]:
[4, 10]
In [129]:
L[1:-2]
Out[129]:
[3, 4]
In [130]:
L[1:-1:2]
Out[130]:
[3, 10]
In [131]:
L
Out[131]:
[2, 3, 4, 10, 11]
In [133]:
L[::-2]
Out[133]:
[11, 4, 2]
In [ ]:
Lm = ["Good bye", 3, print_greetings]

L[i:j] means take i-j elements, starting at i included

In [ ]:
middle = len(Lb)//2
print(middle)
print(Lb[:middle])
print(Lb[middle:])
In [ ]:
pseudo_matrix = [[1,2],[3,4]]
In [ ]:
pseudo_matrix[0][1]

For loops

In [143]:
for i in range(10):
    if i > 5:
        break
    print(i)
0
1
2
3
4
5
In [136]:
L
Out[136]:
[2, 3, 4, 10, 11]
In [139]:
for x in L:
    print(x**2)
4
9
16
100
121
In [140]:
list(range(10))
Out[140]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [142]:
range(10000000000000000000000000000)
Out[142]:
range(0, 10000000000000000000000000000)

Variables

Pointers (two lists), Python tutor? args by reference, copy with list, deep copy?, is, tuples

In [144]:
L = [2,3,4]
In [145]:
L_ = L
In [146]:
L_[0] = 100
In [147]:
print(L_)
[100, 3, 4]
In [148]:
print(L)
[100, 3, 4]
In [149]:
print(L)
[100, 3, 4]
In [150]:
print(L_)
[100, 3, 4]
In [151]:
L is L_
Out[151]:
True
In [152]:
L_copy = L[:]
In [153]:
print(L_copy)
[100, 3, 4]
In [154]:
L is L_copy
Out[154]:
False
In [156]:
import copy
In [ ]:
copy.deepcopy
In [169]:
L.sort()
In [170]:
L
Out[170]:
[2, 3, 4, 10]
In [171]:
L.reverse()
In [172]:
L
Out[172]:
[10, 4, 3, 2]
In [166]:
y  = 10
def add_y(x):
    y = 100
    return x + y
In [167]:
add_y(100)
Out[167]:
200
In [168]:
y
Out[168]:
10
In [165]:
add_y(100)
Out[165]:
120
In [158]:
L = [2,3,4]
In [159]:
add_10(L)
In [160]:
L
Out[160]:
[2, 3, 4, 10]
In [174]:
L + L
Out[174]:
[10, 4, 3, 2, 10, 4, 3, 2]

Linear algebra

array, vectors, matrices, shape, access [3,4], difference with lists, no append, concatenate

Difference vector matrices

In [173]:
V = array([2.,3.,4])
In [175]:
V + V
Out[175]:
array([ 4.,  6.,  8.])
In [176]:
M = array([[2,.3],[1,4]])
In [177]:
print(M)
[[ 2.   0.3]
 [ 1.   4. ]]
In [178]:
V
Out[178]:
array([ 2.,  3.,  4.])
In [179]:
V[0]
Out[179]:
2.0
In [180]:
M[0,0]
Out[180]:
2.0
In [181]:
V
Out[181]:
array([ 2.,  3.,  4.])
In [182]:
V * V
Out[182]:
array([  4.,   9.,  16.])
In [183]:
shape(V)
Out[183]:
(3,)
In [185]:
CV = array([[2.],[3.],[4.]])
In [186]:
print(CV)
[[ 2.]
 [ 3.]
 [ 4.]]
In [187]:
shape(CV)
Out[187]:
(3, 1)
In [188]:
RV = array([[2.,3,4]])
In [189]:
print(RV)
[[ 2.  3.  4.]]
In [190]:
shape(RV)
Out[190]:
(1, 3)
In [192]:
row_0 = [3,4,5.]
In [193]:
M = array([row_0])
In [194]:
print(M)
[[ 3.  4.  5.]]
In [195]:
shape(M)
Out[195]:
(1, 3)
In [196]:
V
Out[196]:
array([ 2.,  3.,  4.])
In [197]:
V.reshape((1,3))
Out[197]:
array([[ 2.,  3.,  4.]])
In [198]:
M = V.reshape((3,1))
Out[198]:
array([[ 2.],
       [ 3.],
       [ 4.]])
In [199]:
T = arange(8).reshape((2,2,2))
In [200]:
print(T)
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
In [201]:
arange(10)
Out[201]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [202]:
array(list(range(10)))
Out[202]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

concatenate

pointwise operations,

dot,

In [204]:
M = arange(4).reshape((2,2))
In [205]:
print(M)
[[0 1]
 [2 3]]
In [206]:
V = array([2,3])
In [207]:
M*V # NOT matrix vector multiplication!!!
Out[207]:
array([[0, 3],
       [4, 9]])
In [208]:
dot(M,V)
Out[208]:
array([ 3, 13])
In [209]:
dot(V,M)
Out[209]:
array([ 6, 11])
In [210]:
dot(V,V)
Out[210]:
13
In [211]:
CV = V.reshape((2,1))
In [212]:
dot(M,CV)
Out[212]:
array([[ 3],
       [13]])
In [214]:
shape(CV)
Out[214]:
(2, 1)
In [215]:
CV.T
Out[215]:
array([[2, 3]])
In [216]:
shape(CV.T)
Out[216]:
(1, 2)
In [217]:
shape(V)
Out[217]:
(2,)
In [218]:
V.T
Out[218]:
array([2, 3])
In [219]:
shape(V.T)
Out[219]:
(2,)
In [222]:
V * V.reshape((2,1))
Out[222]:
array([[4, 6],
       [6, 9]])
In [213]:
dot(CV,M)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-213-c40d19060ea6> in <module>()
----> 1 dot(CV,M)

ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)

shape, .shape. [:,i]. transpose, .T, vector transpose. shape, reshape, column & row matrices. reshape(-1).

(flags?)

Array creation: zeros, ones, empty, eye (identity)

In [224]:
zeros((2,3))
Out[224]:
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
In [226]:
ones((3,2))
Out[226]:
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.]])
In [227]:
identity(3) # eye(3)
Out[227]:
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

Solving linear systems. allclose

In [230]:
print(M)
print(V)
x = solve(M,V)
print(x)
print(dot(M,x))
print(V)
[[0 1]
 [2 3]]
[2 3]
[-1.5  2. ]
[ 2.  3.]
[2 3]

Slicing and shape

Concatenation

Concatenation with concatenate, array, block matrices together, vectors into row or columns.

Plotting

same syntax, no hold, figure, axis('equal'). title, xlabel, ylabel, label, legend.

In [234]:
xs = linspace(0,2*pi,100)
ys = sin(xs)
zs = cos(3*xs)
plot(xs, ys, 'o')
plot(xs, zs, '.')
figure()
plot(xs, ys+.3*zs)
savefig('name.pdf')
In [ ]:
plot(xs,ys)
figure()
plot(xs,zs)
In [ ]:
plot?

0702683132