If you know how to multiply two matrices in NumPy, what would you write in R? The matrix cheat sheet compares the syntax for common operations in MATLAB and Octave, NumPy, R, and Julia.

Sections

Introduction

Matrices (or multidimensional arrays) are not only presenting the fundamental elements of many algebraic equations that are used in many popular fields, such as pattern classification, machine learning, data mining, and math and engineering in general. But in context of scientific computing, they also come in very handy for managing and storing data in an more organized tabular form.
Such multidimensional data structures are also very powerful performance-wise thanks to the concept of automatic vectorization: instead of the individual and sequential processing of operations on scalars in loop-structures, the whole computation can be parallelized in order to make optimal use of modern computer architectures.

Matrix cheatsheet matcheat matrix

Language overview

Before we jump to the actual cheat sheet, I wanted to give you at least a brief overview of the different languages that we are dealing with.

All four languages, MATLAB/Octave, Python, R, and Julia are dynamically typed, have a command line interface for the interpreter, and come with great number of additional and useful libraries to support scientific and technical computing. Conveniently, these languages also offer great solutions for easy plotting and visualizations.

Combined with interactive notebook interfaces or dynamic report generation engines (MuPAD for MATLAB, IPython Notebook for Python, knitr for R, and IJulia for Julia based on IPython Notebook) data analysis and documentation has never been easier.

MATLAB/Octave

Matrix cheatsheet matcheat matlab logo

MATLAB (stands for MATrix LABoratory) is the name of an application and language that was developed by MathWorks back in

  1. One of its strengths is the variety of different and highly optimized “toolboxes” (including very powerful functions for image and other signal processing task), which makes suitable for tackling basically every possible science and engineering task.
    Like the other languages, which will be covered in this article, it has cross-platform support and is using dynamic types, which allows for a convenient interface, but can also be quite “memory hungry” for computations on large data sets.

Even today, MATLAB is probably (still) the most popular language for numeric computation used for engineering tasks in academia as well as in industry.

GNU Octave

Matrix cheatsheet matcheat octave logo

It is also worth mentioning that MATLAB is the only language in this cheat sheet which is not free and open-sourced. But since it is so immensely popular, I want to mention it nonetheless. And as an alternative there is also the free GNU Octave re-implementation that follows the same syntactic rules so that the code is compatible to MATLAB (except for very specialized libraries).

This image is a freely usable media under public domain and represents the first eigenfunction of the L-shaped membrane, resembling (but not identical to) MATLAB’s logo trademarked by MathWorks Inc.

Python NumPy

Matrix cheatsheet matcheat numpy logo

Initially, the NumPy project started out under the name “Numeric” in 1995 (renamed to NumPy in 2006) as a Python library for numeric computations based on multi-dimensional data structures, such as arrays and matrices. Since it makes use of pre-compiled C code for operations on its “ndarray” objects, it is considerably faster than using equivalent approaches in (C)Python.

Python NumPy is my personal favorite since I am a big fan of the Python programming language. Although similar tools exist for other languages, I found myself to be most productive doing my research and data analyses in IPython notebooks.
It allows me to easily combine Python code (sometimes optimized by compiling it via the Cython C-Extension or the just-in-time (JIT) Numba compiler if speed is a concern) with different libraries from the Scipy stack including matplotlib for inline data visualization (you can find some of my example benchmarks in this GitHub repository).

R

Matrix cheatsheet matcheat R logo

The R programming language was developed in 1993 and is a modern GNU implementation of an older statistical programming language called S, which was developed in the Bell Laboratories in 1976. Since its release, it has a fast-growing user base and is particularly popular among statisticians.

R was also the first language which kindled my fascination for statistics and computing. I have used it quite extensively a couple of years ago before I discovered Python as my new favorite language for data analysis.
Although R has great in-built functions for performing all sorts statistics, as well as a plethora of freely available libraries developed by the large R community, I often hear people complaining about its rather unintuitive syntax.

Julia

Matrix cheatsheet matcheat julia logo

With its first release in 2012, Julia is by far the youngest of the programming languages mentioned in this article. a While Julia can also be used as an interpreted language with dynamic types from the command line, it aims for high-performance in scientific computing that is superior to the other dynamic programming languages for technical computing thanks to its LLVM-based just-in-time (JIT) compiler.

Personally, I haven’t used Julia that extensively, yet, but there are some exciting benchmarks that look very promising:

Matrix cheatsheet matcheat julia benchmark

C compiled by gcc 4.8.1, taking best timing from all optimization levels (-O0 through -O3). C, Fortran and Julia use OpenBLAS v0.2.8. The Python implementations of rand_mat_stat and rand_mat_mul use NumPy (v1.6.1) functions; the rest are pure Python implementations.

Bezanson, J., Karpinski, S., Shah, V.B. and Edelman, A. (2012), “Julia: A fast dynamic language for technical computing”.
(Source: http://julialang.org/benchmarks/, with permission from the copyright holder)

Cheat sheet

The NumPy examples use import numpy as np and two-dimensional arrays. In Julia, run using LinearAlgebra, Statistics for the linear algebra and covariance examples. On a narrow screen, scroll each table sideways to see all four languages.

Creating and indexing matrices

The first row creates the same matrix in each language, with 1 and 2 in the first row and 3 and 4 in the second. NumPy starts counting indices at zero. MATLAB, Octave, R, and Julia start at one.

Operation MATLAB / Octave Python / NumPy R Julia
Create a 2 Ă— 2 matrix [1 2; 3 4] np.array([[1, 2], [3, 4]]) matrix(1:4, 2, byrow=TRUE) [1 2; 3 4]
Dimensions size(A) A.shape dim(A) size(A)
First element A(1,1) A[0,0] A[1,1] A[1,1]
First row, kept as a matrix A(1,:) A[:1,:] A[1,,drop=FALSE] A[1:1,:]
First column, kept as a matrix A(:,1) A[:,:1] A[,1,drop=FALSE] A[:,1:1]
Matrix of zeros zeros(m,n) np.zeros((m,n)) matrix(0,m,n) zeros(m,n)
Matrix of ones ones(m,n) np.ones((m,n)) matrix(1,m,n) ones(m,n)
Identity matrix eye(n) np.eye(n) diag(n) Matrix{Float64}(I,n,n)

Reshaping and combining matrices

For the 2 × 2 matrix above, reading down each column gives 1, 3, 2, 4. NumPy’s order="F" uses this column order when reshaping.

Operation MATLAB / Octave Python / NumPy R Julia
Flatten to one row, column by column reshape(A,1,[]) A.reshape(1,-1,order="F") matrix(A,nrow=1) reshape(A,1,:)
Reshape to m rows and n columns in column order reshape(A,m,n) A.reshape(m,n,order="F") matrix(A,m,n) reshape(A,m,n)
Join side by side [A B] np.hstack((A,B)) cbind(A,B) hcat(A,B)
Stack vertically [A; B] np.vstack((A,B)) rbind(A,B) vcat(A,B)

Multiplication and linear algebra

Take the same 2 Ă— 2 matrix and multiply it by itself. The top-left entry of the matrix product is 7 because the first row times the first column gives 1*1 + 2*3. In the element-wise product, the top-left entry is simply 1*1, or 1.

Operation MATLAB / Octave Python / NumPy R Julia
Matrix product A * B A @ B A %*% B A * B
Element-wise product A .* B A * B A * B A .* B
Square each element A.^2 A**2 A^2 A.^2
Square a matrix A^2 np.linalg.matrix_power(A,2) A %*% A A^2
Transpose A.' A.T t(A) transpose(A)
Inverse of a nonsingular matrix inv(A) np.linalg.inv(A) solve(A) inv(A)
Determinant det(A) np.linalg.det(A) det(A) det(A)
Eigenvalues eig(A) np.linalg.eigvals(A) eigen(A)$values eigvals(A)
Sample covariance, observations in rows cov(X) np.cov(X,rowvar=False) cov(X) cov(X)

You can also open the original 2014 worked examples or download the cheat sheet as an image.

Alternative data structures: NumPy matrices vs. NumPy arrays

For two-dimensional NumPy arrays, A @ B and A.dot(B) both compute the matrix product. Use A * B for element-wise multiplication. If you encounter the older np.matrix type, A * B computes the matrix product there, and np.multiply(A, B) gives the element-wise product. NumPy recommends regular arrays for new code. NumPy matrix documentation