Matlab-to-Python

Here are some notes on the Python port itself, as well as some pointers when coming from MATLAB.

Coming From MATLAB

Main differences between writing for MATLAB and writing for Python.

A short overview over the differences between MATLAB and Python as well as a list of corresponing sytax can be found in the scipy wiki (the site is currently unavailable). This presentation gives a more thorough introduction. The most common and important differences are noted below:

  • Matrix multiplication is elementwise (so * in Python corresponds to .* in MATLAB for matrices). Use numpy.dot() for actual matrix multiplication.

  • Matlab accesses matrix elements via A(…), Python uses A[…].

  • Python indexing starts with 0, wheres MATLAB indexing starts with 1. Also for ranges the end value in Python is exclusive, not inclusive as in MATLAB.

    • Example: Let’s say we have a 5x5 matrix A and we want to access the first two columns. In MATLAB we would write

      >>> A(:, 1:2)
      

      which becomes

      >>> A[:, 0:2]
      

      in Python.

  • In Python complex data types (such as matrices) are copied as references only, unless you specifically invoce numpy.copy() on them.

    • Example: We have a matrix A. In MATLAB

      >>> B = A
      

      would give an independent matrix B of A. So

      >>> B(1, 1) = 5
      

      would not change the value in A. In Python

      >>> B = A
      

      would make B a reference to A, so

      >>> B[0, 0] = 5
      

      would change the value in A as well. To get an independent copy in Python use

      >>> B = A.copy()
      
  • Slicing a column or row out of a matrix gives a 1 dimensional array in Python, so you loose the orientation. At the same time, numpy.dot() of two vectors will always result in the scalar product, without the need of transposing the vector first.

  • Two concatenate two matrices in MATLAB you would write:

    >>> C = [A , B]
    >>> D = [A ; B]
    

    In Python you will need to use numpy.c_ and numpy.r_ to concatenate columns or rows respectively:

    >>> C = c_[A, B]
    >>> D = r_[A, B]
    

Changes to ProxToolbox

The problems and data sets are always expanding, but structurally, the biggest change to ProxToolbox is the move from a function in MATLAB to a class in Python. This allows all relevant variables to stay in memory after a single iteration which removes the need to save them in a file in between iterations. Most other changes are related to removing unused code or variables and are noted by a

>>> # PYTHON PORT ANNOTATION

followed by a short description of the change and the reason for it.