#!/usr/bin/env python # coding: utf-8 # Matlab # ==== # # ## Unit 16, Lecture 1 # # *Numerical Methods and Statistics* # # ---- # # #### Prof. Andrew White, March 24, 2016 # Difference between JupyterHub and Your Machine # ---- # # 1. Has many default nbextensions, like spell-check and line numbers # 2. MathJax Chrome bug is fixed # 3. Has Matlab and Python 2 options # 4. Can download nice pdf versions of notebooks # Adding Packages # --- # # You can install packages using either of these two: # # ```python # %system conda install [package] # %system pip install [package] # ``` # # These will persist as long as your files in `local` # Switching between programming languages # --- # # You can switch between the different programming languages using the `%%matlab` or `%%python` cell magic. It's best to use the python 3 kernel and switch as needed, unless you're exclusively using matlab or R # Matlab # === # # Matlab is a proprietary programming language and suite of tools made by Mathworks. Matlab is the most commonly used alternative to Python in engineering. It is generally more common than Python in engineering. It is usually used through the Matlab application, which is a java-based program. # Starting Matlab in a notebook # --- # # We're going to be using Matlab in Jupyter notebooks. Here's how you enable matlab in a python notebook. Note, you can also just start a Matlab notebook # In[1]: #you must do this to enable Matlab in a non-matlab notebook get_ipython().run_line_magic('load_ext', 'pymatbridge') # Matlab Basics # --- # # Matlab has very similar syntax to Python. The main difference in general arithmetic is that Matlab includes all the math/array creation functions by default. Let's compare some examples # In[2]: #Python import numpy as np b = 4 x = np.linspace(0,10, 5) y = x * b print(y) # In[3]: get_ipython().run_cell_magic('matlab', '', '\nb = 4;\nx = linspace(0,10,5);\ny = b .* x\n') # There are three main differences we can spot: # # * Matlab doesn't require any imports or prefixes for linspace # * Matlab requires a `;` at the end to suppress output. If you don't end with a `;`, Matlab will tell you about that line. # * In `numpy`, all arithmetic operations are by default element-by-element. In Matlab, arithmetic operations are by default their matrix versions. So you put a `.` to indicate element-by-element # Working with matrices # === # # $$ # \left[\begin{array}{lr} # 4 & 3\\ # -2 & 1\\ # \end{array}\right] # \left[\begin{array}{c} # 2\\ # 6\\ # \end{array}\right] # = # \left[\begin{array}{c} # 26\\ # 2\\ # \end{array}\right] # $$ # In[4]: x = np.array([[4,3], [-2, 1]]) y = np.array([2,6]).transpose() print(x.dot(y)) # In[5]: get_ipython().run_cell_magic('matlab', '', "\nx = [4, 3; -2, 1];\ny = [2,6]';\nx * y\n") # You can see here that Matlab doesn't distinguish between lists, which can grow/shrink, and arrays, which are fixed size # In[6]: x = [2,5] x.append(3) x # In[7]: get_ipython().run_cell_magic('matlab', '', '\nx = [5,2];\nx = [x 3]\n') # Since Matlab variables are always fixed length, you must create new ones to to change size # Many of the same commands we used have the same name in matlab # In[25]: import scipy.linalg as lin example = np.random.random( (3,3) ) lin.eig(example) # In[27]: get_ipython().run_cell_magic('matlab', '', '\nexample = rand(3,3);\neig(example)\n') # Slicing # --- # # Slicing is nearly the same, except Matlab starts at 1 and includes both the start and end of the slice. Matlab uses parenthesis instead of brackets # In[8]: get_ipython().run_cell_magic('matlab', '', '\nx = 1:10;\n%this is how you make comments BTW, the % sign\nx(1) \nx(1:2)\nx(1:2:5) \n') # In[9]: x = list(range(1,11)) print(x[0]) print(x[0:2]) print(x[0:6:2]) # Program flow control # --- # # All the same flow statements from Python exist # In[10]: for i in range(3): print(i) print('now with a list') x = [2,5] for j in x: print(j) # Matlab can only iterate in for loops on integers. Thus, to iterate over elements of an array, you need use this syntax: # In[11]: get_ipython().run_cell_magic('matlab', '', "\nfor i = 0:2\n i\nend\n'now with a list'\nx = [2, 5]\nn = size(x)\nfor j = 1:n\n j\nend\n") # If statements are similar. `and` is replaced by `&`, `or` by `|` and `not` by `~` # In[12]: get_ipython().run_cell_magic('matlab', '', "\na = -3;\n\nif a < 0 & abs(a) > 2\n a * 2\nend\n\nif ~(a == 3 | a ~= 3)\n 'foo'\nend\n") # Creating functions in Matlab # --- # # In Matlab, you always define functions in another file and then read them in. You can use the `writefile` cell magic to do this # In[13]: get_ipython().run_cell_magic('writefile', 'compute_pow.m', 'function[result] = compute_pow(x, p)\n%this function computes x^p\nresult = x ^ p;\n') # In[14]: get_ipython().run_cell_magic('matlab', '', 'compute_pow(4,2)\n') # If you modify the file, you have to force matlab to reload your function: # In[15]: get_ipython().run_cell_magic('matlab', '', '\nclear compute_pow\n') # Plotting # === # # The matplotlib was inspired by Matlab's plotting, so many of the functions are similar. # In[21]: import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') x = np.linspace(0,10,100) y = np.cos(x) plt.figure(figsize=(7,5)) plt.plot(x,y) plt.grid() plt.xlabel('x') plt.ylabel('y') plt.title('cosine wave') plt.show() # In[20]: get_ipython().run_cell_magic('matlab', '', "\nx = linspace(0,10,100);\ny = cos(x);\n\nplot(x,y)\ngrid on\nxlabel('x')\nylabel('y')\ntitle('cosine wave')\n") # Example - Solving and plotting an Optimization Problem # --- # # Minimize # # $$f(x) = (x - 4)^2 $$ # In[48]: from scipy.optimize import * def fxn(x): return (x - 4)**2 x_min = newton(fxn,x0=0) plt.figure(figsize=(7,5)) x_grid = np.linspace(2,6,100) plt.plot(x_grid, fxn(x_grid)) plt.axvline(x_min, color='red') plt.show() # In[39]: get_ipython().run_cell_magic('writefile', 'my_obj.m', 'function[y] = my_obj(x)\n%be careful to use .^ here so that we can pass matrices to this method\ny = (x - 4).^2;\n') # In[47]: get_ipython().run_cell_magic('matlab', '', "\n[x_min, fval] = fminsearch(@my_obj, 0);\n\nx_grid = linspace(2,6,100);\nplot(x_grid, my_obj(x_grid));\nhold on\nylimits=get(gca,'ylim');\nplot([x_min, x_min], ylimits)\n") # There are a few key differences to note: # # 1. When referring to a function in matlab, you have to put an `@` if you're not calling it # 2. There is not an easy way to plot a vertical line in matlab, so you have to plot a line from the lowest y-value to highest y-value # 3. Be careful about making sure your function can handle matrices # Learning Matlab # --- # # You currently know many numerical methods. The key to learning Matlab is using their online documentation and judicious web searches. For example, if you want to solve two equations you know you could use a root-finding method. A bing search would bring you to the `fsolve` method. # Excel # === # # Excel is a pretty self-explanatory program. I'm just going to show you some advanced things which you may not already know. # # * References # * Dragging equations # * Auto-fill # * Optimization -> solver add-in # * Statistics -> data analysis add in for rn # * Matrix-functions -> ctrl-shift # * Text parsing -> past-special, to delete blanks go to find-select and then delete # * Importing data from Excel # Pandas # --- # # Pandas is a library that can read data from many formats, including excel. It also has some built in graphing/analysis tools. # In[12]: import pandas as pd data = pd.read_excel('fuel_cell.xlsx') data.info() # You can access data in two ways: # In[10]: data.Resistance[0:10] # In[11]: data.ix[0:10, 3] # In[ ]: get_ipython().run_line_magic('system', 'jupyter nbconvert unit_10_lecture_1.ipynb --to slides --post serve') # In[ ]: