Invoking and Starting MATLAB

Video

Motivation

MATLAB is a technology that you may have to use one day, and I received a fair amount of pressure from the faculty to include it. Note that I have yet to hear someone in math industry even bring it up. While I consider myself proficient in it, it is not a common technology for me to use, and I would recommend never starting a wholly new project in it; There are still a few valid reasons to use it.

The main reason being, MATLAB is full of legacy code for specialized applications - harvested from researchers for free and available for considerable fees to the MATLAB corporation due to an absurd licensing scheme - that can be invaluable in engineering and certain applied mathematics domains.

Today our main focus will be on how you can run MATLAB (legally) without buying it - and transition into basic MATLAB, and how you can run MATLAB as part of a python workflow.

Access Methods

SSH Command Line

MATLAB can be executed on the command line from an installed machine (such as banach) with:

matlab -nodisplay -nodesktop

Or, to run a file (with a .m extension),

matlab -nodisplay -nodesktop -r filename

Specifying the filename without the .m file extension.

Graphical Options

Outdated Options

To run the famous MATLAB notebook Graphical User Interface, you have a couple options. You could use X11 Window Forwarding or Purdue GoRemote Software, both of which are frustratingly slow and have strange configurations.

Modern Options

Alternately, several Purdue departments and research groups offer ThinLinc remote desktops, or Windows Remote Desktops.

Note that many of these clients require use of the Purdue VPN, as will the Math Department's in the fall.

For a graphical connection, the Purdue Math ThinLinc is likely your current best option for experimenting.

Remember that for running serious computations, you should use a command-line connection to a dedicated compute server which you discuss with your advisor.

GNU Octave

GNU Octave is a strange beast - basically, a Free and Open Source implementation of the core MATLAB functionality and several common toolkits.

It cannot be relied upon to behave just like MATLAB, and it doesn't have as wide a variety of tools, but is an excellent option for executing, practicing or preparing most MATLAB-like scripts without paying for (or supporting) official MATLAB.

There is a rough list of differences on WikiBooks.

For the things we will be discussing today, they will be roughly equivalent - so I will be using an Octave Jupyter Kernel for the demonstrations today.

If you want to install it on your computer, there are a few steps of varying difficulty:

  • Download and install octave from your package manager, or from the GNU webpage.
  • (on windows) Add the {install path}/Octave/Octave-5.2.0/mingw64/bin directory to your system PATH, customizing according to your install position
  • Install from pip or your package manager the package octave_kernel
  • Install the language-matlab-octave Atom package via apm or your settings
  • Restart Atom

However, you can do all you need to for now on banach, so a full install is not necessary.

Using MATLAB

The NumPy project has put together a handy document to help people familiar with MATLAB use NumPy.

It is remarkably useful for the other direction, as well, should you want to. NumPy owes a lot of inspiration to MATLAB - both for what to do and what not to do - so the translation is surprisingly easy.

Datatypes

MATLAB, built on the same technology as NumPy, mostly supports the same datatypes.

However, using anything other than double-precision floating point numbers is likely to cause various unpleasant surprises - from hidden overflows, to many basic functions or algorithms straight up refusing to run.

For example, trying to square an integer matrix:

int64([0 1;2 3])^2

Returns the error:

MPOWER (^) is not fully supported for integer classes. Both arguments must be scalar. Use POWER (.^) for elementwise power.

This basic functionality is far from the only functionality missing for datatypes other than a plain double floating point number.
The consolation is that - in general - a double is enough for math and engineering, and so you should probably consider MATLAB to have one datatype, and look to other tools if you need much greater or lesser precision.

Constructing Matrices

The main area where MATLAB receives praise is in its simple, compact for creating matrices:

mat=[1 2;3 4]

In general, matrices are two-dimensional (even when passed a single row) - unlike the n-dimensional ndarrays.

Types are generally assigned by casting afterwards:

mat=double([1 2;3 4])
Name example description
Explicit Matrix [1 2;3 4] arrays from lists of lists
Zero Matrix zeros(3,3) empty (zero) arrays
Constant Matrix ones(3,3) one arrays
Identity eye(3) The $n \times n$ identity matrix.
Range [1:.5:9] double-closed range (unlike numpy.arange)
Subdivided Range linspace(0,100,5) basically numpy.linspace.

Reshaping matrices is fairly similar; however, MATLAB is not particularly object-oriented, so what would be a method is a separate function:

reshape([1:9],3,3)

Like in NumPy, there are also a variety of utility functions for the construction of matrices:

Operation Math Example Notes
Diagonal $\operatorname{diag}(1,2,3)$ diag([1 2 3]) If called on a matrix, returns the diagonal entries.
Matrix Tensor (Kronecker Product) $A \otimes B $ kron(A,B) Standard basis is dictionary ordering.
Block $\begin{bmatrix} A &B \\ C& D\end{bmatrix}$ [A B;C D]
Block Diagonal $\begin{bmatrix} A && 0 \\ & B \\ 0 && C \end{bmatrix}$ blkdiag(A,B,C)

Operating on Matrices

Matrices in MATLAB try their best to be analagous to mathematical objects, and as such, the basic operators +,-,*,^ work as matrix operations, as in math.

To get the entrywise multiplication or exponentiation, use the dot-operators .*,.^.

There are a wide variety of mathematical functions, such as eig([1 1;1 1]), which you can search the docs for as per your needs. (the built-in help is broken in the current version of MATLAB on banach.) There is also a postfix operator ' which gets the conjugate transpose of a matrix, since that is a common desire.

To read or change particular values, MATLAB supports a similar slice notation.

m = ones(3)
m[2,2]=-8

Note that MATLAB is 1-indexed (as mathematics often is).

Using MATLAB (from Python)

There are countless ways to access the power of MATLAB without having to use it very much. Sage has a robust MATLAB interface, part of its large suite of interoperability tools, but we are not installing Sage in this course. However, it may be one of the most convenient ways of using MATLAB indirectly (which you should consider an indictment of MATLAB.)

Sharing Data

By File

One traditional, simple, and very effective way is to write arrays to files - such as simple .csvs - to pass them between MATLAB and Python sessions:

import numpy
matrix = numpy.arange(4).reshape((2,2))
numpy.savetxt("matrix.csv",
    matrix,
    fmt="%d",
    delimiter=",")

Which you can then call MATLAB on, do some computations, and pass back:

mat = csvread("matrix.csv")
mod_mat = mat^2
csvwrite("modified_matrix.csv",mod_mat)

To pull into NumPy:

modified_matrix = numpy.loadtxt("modified_matrix.csv",delimiter=",")

For easy reading of more complex data by MATLAB, scipy.io.savemat and scipy.io.loadmat create and read MATLAB-style .mat files - from and to python dictionaries.

This can pass higher dimensional data, and multiple variables in the same file - but is less readable, and there are some version issues.

Subprocess Execution

You can even invoke a MATLAB script from Python with the os module. Suppose we have some matlab proccess as example_proccess.m:

load("example.mat")
mod_mat = mat.^2
save modified_example.mat mod_mat
exit

Then we could apply it to a numpy matrix:

from scipy.io import savemat,loadmat
import numpy
import os
mat = numpy.arange(4).reshape((2,2))
savemat("example.mat",{"mat":mat})
os.system("matlab -r example_proccess -nodisplay -nodesktop")
mod_mat = loadmat("modified_example.mat")["mod_mat"]
print(mod_mat)

We can suppress the output from MATLAB by adding semicolons to the end of all the lines.

It may be worthwhile, if constructing commands, to use the more newer and more complicated, but versatile, subprocess module:

subprocess.call(["matlab",
                 "-r",
                 "example_proccess",
                 "-nodisplay",
                 "-nodesktop"])

Official matlab Module

Mathworks have created their own MATLAB Interface.

It is a headache to set up, only works in a depreciated version of python, and has a very strange interface, but allows you to connect python to a running MATLAB session and pass matrices back and forth, as well as call standard commands.

It's not so much fun, to get working or to use, but allows for relatively space-efficient translation.

Assignment

Today's assignment is to create the familiar matrix:

\[ \begin{bmatrix} 1 & 4 & 7 & 2 & 0 & 0 & 1 \\ 2 & 5 & 8 & 0 & 2 & 0 & 2 \\ 3 & 6 & 9 & 0 & 0 & 2 & 3 \\ 0 & 0 & 0 & 1 & 7 & 0 & 0 \\ 0 & 0 & 0 & 0 & 2 & 6 & 0 \\ 0 & 0 & 0 & 0 & 0 & 3 & 5 \\ 0 & 0 & 0 & 0 & 0 & 0 & 4 \end{bmatrix} \]

in MATLAB, using MATLAB matrix assembly tools.

Graded Assignment: Upload a .m file which constructs the target matrix, built from the matrix constructors rather than explicitly.

Department of Mathematics, Purdue University
150 N. University Street, West Lafayette, IN 47907-2067
Phone: (765) 494-1901 - FAX: (765) 494-0548
Contact the Webmaster for technical and content concerns about this webpage.
Copyright© 2018, Purdue University, all rights reserved.
West Lafayette, IN 47907 USA, 765-494-4600
An equal access/equal opportunity university
Accessibility issues? Contact the Web Editor (webeditor@math.purdue.edu).