Orad’s python guide for dummies

(and people familiar with MATLAB)

1. Introduction 2

2. Installing python 2

Install Anaconda 2

Install Spyder 3

Install matplotlib and numpy 4

3. Language differences between MATLAB and Python/numpy/matplotlib 5

Major differences 5

Minor differences 6

A warning about lists 7

4. Plotting using matplotlib 8

Simple plot 8

Subplots 9

Dynamic plots with sliders 10

5. Saving and loading data 11

Importing from a *.csv file 12

Import/exporting *.mat files in python 13

6. Defining functions 13

Multiple functions in a single file 14

7. Built-in physical constants 15

8. Fitting 15

Installing the lmfit package 15

Actually fitting 16

9. New data types 18

Lists 18

List comprehension 18

Dictionaries 19

Other things I want to learn 19

Making python fast 19

Interfacing with hardware 19

1. Introduction

Orad, why are you doing this to yourself? You’re already so good at MATLAB!

Python is completely free, MATLAB is not. We can easily install python on any new student’s computer or any computer in the lab. Basically, I’m tired of “looking for licenses,” and the longer I support using MATLAB the harder the transition will be as we accumulate more “institutionalized” codes in *.m files. Secondly, python is one of the most popular general purpose programming languages out there, so by learning it, you are improving your job prospects. You will be able to program actual things (programs, website, etc) and not just scientific computing things.

I’m not a hard-core programmer. I mostly want to do simple algebraic calculations, fits, solve the occasional differential equation, and plot my data. I want a MATLAB (and perhaps a Labview) replacement, so that will be the scope of this document as I learn.

I am building this document in chronological order, so as I learn more things I will add them to the bottom. This means that if you follow this document in this order, you should hopefully not be surprised by unfamiliar components earlier on.

If you found this useful, or have some suggestions on what to add (or correct), don’t hesitate to message me @Orad on twitter or at my e-mail [email protected]

2. Installing python

Install Anaconda

Python itself is a programming language, not a programming environment. This means there isn’t a standard “python programming window” like there is in MATLAB. I want a desktop environment that looks as much like MATLAB as possible, which supposedly is a program called Spyder. The best way to get Spyder is to install Anaconda, which is a program that looks like this:

You can clearly see that Anaconda provides many environments that can use Python. Many people recommend “jupyter notebook,” since that gives a more “notebook”-ey environment that you might be familiar with if you use Mathematica. I’ve also heard that Pycharm is good. I don’t know much about the rest, and I didn’t feel like experimenting. As I mentioned before, I have been using Spyder.

Install Spyder

From that Anaconda page, you can select “install Spyder,” which looks like this

Looks MATLAB-ey right?

If you ever want to open Spyder, you always need to open Anaconda first. If you are clever and google it, you can find ways to open Spyder directly, but for now this extra step doesn’t bother me.

Install matplotlib and numpy

As I mentioned before, python itself is just a general purpose programming language. It can do everything but isn’t meant to do anything. I have learned that this is both good and bad — it’s good because when you turn it on to run your code, it isn’t bothering to load any code you aren’t planning on using, so it can be relatively lightweight. It’s also good because right at the top of your code you can tell which packages it’s planning on using. It’s bad because in a sense it’s not specialized at anything, so it will never be as fast as, say, MATLAB at matrix multiplications.

To “specialize” your python installation to do MATLAB-ey operations, you need to install 2 packages. Click on “Environments” in Anaconda, and search for numpy (MATLAB replacement for manipulating arrays and matrices) and then matplotlib (MATLAB replacement for plotting):

If you try to install either, Anaconda will show you a pop-up to recommend you install other packages that those 2 rely on. I just accepted and installed those too.

3. Language differences between MATLAB and Python/numpy/matplotlib

Here I will just collect things that annoyed me that I learned as I went along. Also, someone on twitter shared this cheatsheet with me. There’s also a very comprehensive list of all the MATLAB commands and their python or numpy equivalents here.

Major differences

* Tabbing and indentation doesn’t matter at all in MATLAB. It’s super critical in python. For example, in MATLAB every “For” loop has a matching “end”. Python knows where the for-loop finishes based on when you stop tabbing. In MATLAB you’d have:

* for i = 1:10

Do something

end

Do something else.

Whereas in python it’s:

* for i in range(1,10)

Do something

Do something else.

So everything in python is defined by how “tabbed out” it is.

* Some functions in python are actually methods. So instead of functions being like sum(a), in numpy you need to do a.sum().

* In python there are arrays and matrices. Those are 2 different things. Read this for an explanation of the difference. I will try and use arrays based on its recommendations. (Also there are lists.)

* Many commands can’t be used without calling their package first. So, for example, in MATLAB you would just say a = linspace(0,10,100) to create an equally spaced array. Because the linspace command is only native to the numpy package, and not to python itself, you need to first import numpy, and then call linspace as a subfunction of numpy, so:

* import numpy as np

* a = np.linspace(0,10,100)

In python, “linspace” on its own just doesn’t mean anything.

* Python has a kernel. I’m not 100% what that means, but I noticed that just clicking “clear all” like you do in matlab doesn’t actually restart everything. It sort of makes sense — when you import a package it remains “in memory” in python. So if you really want to restart fresh, you need to restart the kernel. To do that in Spyder it’s under Consoles:

Minor differences

* A large list of the minor syntactic differences can be found here:

https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html#linear-algebra-equivalents

* Matrices/arrays in MATLAB are 1-indexed (so the first element in the matrix a is a(1)) whereas in python they’re 0-indexed (so a[0]).

* More on indexing — the last number is excluded. Suppose a[1,2,3], then a[0:2] will ONLY return [1,2]. It excludes a[2]!

* There is a difference between a 2D nx1 and a 1D n array. It sounds crazy, I know. MATLAB doesn’t make a distinction between these two things. You can tell what type of array a is by using print(a.shape()). A 2D 100x1 array will output (100,1). A 1D 100 array will output (100,). The reason this is important is because if you multiply or divide one by the other you’ll get a 100x100 result... which is likely not what you want. To turn a (100,1) to a (100,) array you can use the np.squeeze command.

* The last element of an array isn’t “end” like in MATLAB. It’s (get this) -1. So instead of a(end) you’d say a[-1].

* Oh yea, they also use square brackets. Parenthesis () are reserved for function-calls.

* Python doesn’t need semicolons like MATLAB does. If you want to display something, you need to explicitly ask for it. So in MATLAB you would go just say a to make it output the contents of the variable a, in python you’d say print(a).

* The exponent symbol (‘^’ in MATLAB) is **, so 10^2 is 10**2

* Comment start with # not %. If you want an individual code cell (this might be a spyder-specific thing, but it mimics some MATLAB functionality) you need 2 %%s just like in MATLAB. So together, the beginning of a cell will have

# %% This is the start of a cell

A warning about lists

This here is a disclaimer, more than anything else. Hopefully I’ll save a few minutes of your time.

This line will create a list:

* a = [1,2,3,4]

It is not an array. It might look like an array, but it’s not an array! 2*a does NOT give [2,4,6,8], but [1,2,3,4,1,2,3,4]!!!

I don’t quite understand how lists work quite yet (turns out I’ll get to that later). What’s nice about them is that they can hold anything — string, float, whatever, even other lists. So let’s work this out with an example. Let’s put the list a from above into another list. So:

* b = [a,1]

Will give you this:

[[1, 2, 3, 4], 1]

So here, the list a is inside another list. If you want to access an element inside that first list a from b, you can do it 2 ways. The first is ask for the first element of b, and then the element of a of that you want:

* b[0]

a[2]

will give you 3.

The second way is cleaner — you use use 2 sets of square brackets, so:

* b[0][2]

The reason I have found this is important because sometimes you’ll import data from a *.mat file and python will convert it into lists of lists of lists for some reason. This is just good to know in advance. I literally have a variable called “mat_contents[0][0][0][4][0][0]” somewhere because of the weird way it was imported.

Lists are probably very important to python, but I haven’t completely figured them out yet.

4. Plotting using matplotlib

If you want to use matplotlib, you need to import it at the beginning of every single script. Get used to it, I guess. This link has literally everyt