UP | HOME

Chapter XXX: Python for Matlab / Octave programmers

$Id: kurt-2010.org 13030 2010-01-14 13:33:15Z schwehr $

Table of Contents

from Octave / Matlab

Summary table with matlab/ octave and python as two columns that cover this nextbsection

comment character

Matlab starts comments with todo

Todo put in a matlab comment example or two

Python starts comments with a pound / hash character

1 + 3# comments can start in a line and to to the end

strings

arrays and matrices

Matlab thinks about the world as matrices. There 1d matrices are arrays. In python, we have a lot more flexibility with types of data, but first, we will compare mat lab's types to the same things found in python. First, let us consider a 1D array/matrix from mat lab. The core of python has three ways that you could represent that array. The simplest is called a tuple (todo def), which is a series of items between parentheses. Here are some simple cases of tuples. First the matlab.

Matlab:

a = [ 1 ]
b = [ 1 2 3 9 ]
c = [ 1 3 5 NaN 11 ]
D = todo a veer sparse list

Python:

a = ( 1, ) #. The comma is not required, but I put it in to make it obvious this is a tuple
b = ( 1, 2, 3, 9 )
C = ( 1, 3, 5, None, 11)
D = todo a very sparse list

In python, the tuple is is read only data typebfor speed. You can change a variable that is a tuple by assigning another tuple to it, but the tuple can't change once it has need created, it is "immutable". This let's python save memory and run faster.

If you need to be able to mobility an array over time, you can keep creating new tuples and replace them into the variable. Python will get rid of the old tuple for you.

A = (1,) + (3, 5) 
A = b + ( 4, 7 )

Accessing elements in an matlab array or python tuple

Compare the two todo

lists

If you will be changing a variable containing a tuple often, you might want to switch to a list. Lists will run a bit slower, but allow you to modify them on the fly without creating a new list. Lists can do everything that a tuple can, but

simple reading from a file

Matlab data can be loaded like so

Todo

In python we can read data a couple of ways

Read all is slow

For loop

Arrays

Mmap. The is very advanced, but actually turns out to often make your code very simple

decoding binary data

Have an example and load it both in matlab and python

Author: Kurt Schwehr

Date: $Date: $

HTML generated by org-mode 7.3 in emacs 23