#!/usr/bin/env python # coding: utf-8 # ## Lecture for the course [Python for MATLAB users](http://sese.nu/python-for-matlab-users/), by Olivier Verdier # We begin by importing scientific packages in the global namespace: # In[2]: get_ipython().run_line_magic('pylab', '') # We tell `matplotlib` to plot inside this notebook. # In[3]: get_ipython().run_line_magic('matplotlib', 'inline') # ## Notebook # Shift+enter, help, save, `%whos`, `%pylab`, `%debug`, text+Python, up-downloadable, [Python notebook for matlab users](http://xcorr.net/2013/04/19/ipython-and-ipython-notebook-for-matlab-users/), [Nature article](http://www.nature.com/news/interactive-notebooks-sharing-the-code-1.16261), 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) # In[7]: i # In[9]: Out[7] + 10 # In[10]: type(i) # In[14]: get_ipython().run_line_magic('whos', '') # In[15]: f = 2.3 # In[16]: type(f) # In[17]: f + i # In[18]: print(type(1)) print(type(1.)) # In[19]: z = 1. + 2.j # In[20]: print(z) # In[21]: J = 1.j # In[22]: 2 + 3*J # In[24]: type(2+3j) # In[25]: z # In[27]: z.real # In[28]: z.imag # In[30]: z.conjugate() # In[31]: get_ipython().run_line_magic('whos', '') # In[32]: f * i # In[33]: f + i # In[34]: 2^3 # In[35]: 2**3 # In[36]: 2/3 # In[37]: 2//3 # In[38]: 10//4 # In[42]: print(10.1//4.1) print(floor(10.1/4.1)) # In[43]: # comment # In[ ]: # In[ ]: # In[ ]: # In[44]: pi # ## Strings # Double, single quotes, triple, escape (`\`), concatenation (`+`), interpolation (`%`, `format`) # In[49]: s = "hello " # In[50]: me = "Olivier" # In[51]: s + me # In[60]: template = "Hello {}, my name is {}" # In[61]: template.format("Olivier", "Jupyter") # In[ ]: # In[54]: template.format("Åsa") # In[55]: s_ = 'single quotes instead' # In[56]: s__ = "I'm happy" # In[58]: print(s) print(s__) # In[ ]: s = """Three quotes with return inside another one """ # In[63]: s = "hello, \nI'm happy" print(s) # In[ ]: # ## 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") # In[69]: a # 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]: get_ipython().run_line_magic('pinfo', 'add_prod') # In[74]: r = add_prod(2,3) # In[75]: print(r) # In[76]: r[0] # In[77]: r[1] # In[ ]: # In[73]: print(s,p) # In[ ]: # In[ ]: # In[104]: def greetings(name): template = "Hello {}, how are you??" print(template) print("still in function") print("I'm outside the function") # In[86]: greetings(3) # 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()) # In[ ]: # In[99]: x = print_greetings # In[100]: print(x) # In[101]: x() # In[ ]: # In[89]: print_greetings() # function execution # In[90]: print_greetings # just the function # In[102]: def execute(f): f() # In[103]: execute(print_greetings) # In[ ]: # 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[ ]: # In[110]: def inside(x): if (x < 0) and (x > -1): return "fantastic" else: return "too bad" # In[112]: inside(-.5) # In[113]: 2 > 3 or 10 > 5 # In[114]: not 3 < 5 # In[ ]: # In[109]: sign(-.5) # In[106]: sign(3) # In[107]: sign(-1) # In[ ]: # ## Lists # `[]`, accessing (from zero!), altering, `append`, `len`, concatenate `+`, and `*`, slicing `:`, last element `-1` # In[115]: L = [2, 3, 4] # In[116]: L[0] # In[117]: L[1] # In[118]: len(L) # In[119]: L.append(10) print(L) # In[120]: L.append("hello") print(L) # In[121]: L[4] = 11 print(L) # In[122]: L[-1] # In[123]: L[-2] # In[124]: L[-0] # In[125]: L # In[126]: L[1:4] # In[127]: L[1:-1] # In[128]: L[2:-1] # In[129]: L[1:-2] # In[130]: L[1:-1:2] # In[131]: L # In[133]: L[::-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) # In[136]: L # In[139]: for x in L: print(x**2) # In[140]: list(range(10)) # In[142]: range(10000000000000000000000000000) # ## Variables # Pointers (two lists), [Python tutor](http://www.pythontutor.com/visualize.html#mode=edit)? 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_) # In[148]: print(L) # In[149]: print(L) # In[150]: print(L_) # In[151]: L is L_ # In[152]: L_copy = L[:] # In[153]: print(L_copy) # In[154]: L is L_copy # In[156]: import copy # In[ ]: copy.deepcopy # In[169]: L.sort() # In[170]: L # In[171]: L.reverse() # In[172]: L # In[ ]: # In[166]: y = 10 def add_y(x): y = 100 return x + y # In[167]: add_y(100) # In[168]: y # In[165]: add_y(100) # In[158]: L = [2,3,4] # In[159]: add_10(L) # In[160]: L # In[174]: L + L # In[ ]: # ## 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 # In[176]: M = array([[2,.3],[1,4]]) # In[177]: print(M) # In[178]: V # In[179]: V[0] # In[180]: M[0,0] # In[181]: V # In[182]: V * V # In[183]: shape(V) # In[185]: CV = array([[2.],[3.],[4.]]) # In[186]: print(CV) # In[187]: shape(CV) # In[188]: RV = array([[2.,3,4]]) # In[189]: print(RV) # In[190]: shape(RV) # In[192]: row_0 = [3,4,5.] # In[193]: M = array([row_0]) # In[194]: print(M) # In[195]: shape(M) # In[196]: V # In[197]: V.reshape((1,3)) # In[198]: M = V.reshape((3,1)) # In[199]: T = arange(8).reshape((2,2,2)) # In[200]: print(T) # In[201]: arange(10) # In[202]: array(list(range(10))) # `concatenate` # pointwise operations, # `dot`, # In[204]: M = arange(4).reshape((2,2)) # In[205]: print(M) # In[206]: V = array([2,3]) # In[207]: M*V # NOT matrix vector multiplication!!! # In[208]: dot(M,V) # In[209]: dot(V,M) # In[210]: dot(V,V) # In[211]: CV = V.reshape((2,1)) # In[212]: dot(M,CV) # In[214]: shape(CV) # In[215]: CV.T # In[216]: shape(CV.T) # In[217]: shape(V) # In[218]: V.T # In[219]: shape(V.T) # In[222]: V * V.reshape((2,1)) # In[213]: dot(CV,M) # `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)) # In[226]: ones((3,2)) # In[227]: identity(3) # eye(3) # Solving linear systems. `allclose` # In[230]: print(M) print(V) x = solve(M,V) print(x) print(dot(M,x)) print(V) # 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[ ]: get_ipython().run_line_magic('pinfo', 'plot') # 0702683132