Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 45 ยท Practice and Review

MATLAB, Octave and Python Compared

Compare MATLAB, GNU Octave and Python with NumPy side by side: syntax differences, portable code, Octave-only and MATLAB-only features, and translation tips.

MATLAB, GNU Octave and Python with NumPy solve the same kind of problem, and a person who knows one can read the other two after an afternoon of study. They are not interchangeable, though. Octave aims to run MATLAB programs, and mostly succeeds. Python with NumPy and SciPy covers the same numerical ground, but its syntax and a few key conventions differ in ways that cause silent bugs.

This lesson is a map for three journeys: writing code that runs on both MATLAB and Octave, moving from MATLAB to Python, and moving from Python to MATLAB. MATLAB and Octave do not run in your browser here, so the MATLAB lines are read-only; the Python stand-ins run for real and show the translations. Everything in this lesson builds on the tutorial so far, so follow the links when a topic feels new.

Three tools, one family

MATLAB Commercial, polished, toolboxes and Simulink.
Octave Free, mostly MATLAB-compatible.
Python Free, general-purpose, NumPy for arrays.
1 / 2

The big three differences

Indexing. MATLAB and Octave count from 1 and ranges include both ends: x(1:3) is the first three elements. Python counts from 0 and the end of a slice is excluded: x[0:3]. The last element is x(end) in MATLAB and x[-1] in Python. Brackets differ too: MATLAB indexes with parentheses, Python with square brackets.

Operators. In MATLAB, A*B is the matrix product and A.*B is element-wise. In NumPy it is the other way round: A*B is element-wise and A @ B is the matrix product. Writing A*B while thinking in the other language is the most common translation bug (see Arithmetic: Matrix vs Element-wise). The power operator has the same trap: A^2 versus A**2.

Memory order. MATLAB stores matrices column by column, so A(:) walks down the first column, then the second. NumPy stores row by row by default. This affects reshape and linear indexing: to reproduce MATLAB's reshape(1:6, 2, 3) in NumPy you must pass order="F".

Python The big three, side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A translation table

This table covers the operations you use every day. The Octave column differs from MATLAB only where noted.

Task MATLAB / Octave Python with NumPy
First element x(1) x[0]
Last element x(end) x[-1]
Slice 2 to 4 x(2:4) x[1:4]
Row 2 of a matrix A(2, :) A[1, :]
Matrix product A*B A @ B
Element-wise product A.*B A * B
Transpose A' (conjugate), A.' A.T (use A.conj().T for conjugate)
Solve Ax = b A\b np.linalg.solve(A, b)
Size size(A), numel(A) A.shape, A.size
Range 0:0.1:1 np.arange(0, 1.1, 0.1) or np.linspace(0, 1, 11)
Zeros matrix zeros(3, 4) np.zeros((3, 4))
Mean of columns mean(A) (dim 1) A.mean(axis=0)
Indices where true find(x > 3) np.nonzero(x > 3)[0]
Concatenate [a, b], [a; b] np.hstack, np.vstack
Comment % text # text
Not equal ~= (also != in Octave) !=
Logical not, and, or ~, &, | ~, &, | on arrays; not, and, or on scalars

Two traps hide in this table. First, mean(A) in MATLAB reduces along the first non-singleton dimension (columns for a matrix), which is axis=0 in NumPy, but for a row vector MATLAB reduces along dimension 2, while axis=0 of a 1-D NumPy array is its only axis. Second, end and -1 look alike but only MATLAB's end works inside ranges like x(end-2:end); the NumPy equivalent is x[-3:].

Python Translate five MATLAB lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing code that runs in both MATLAB and Octave

Octave runs most MATLAB code unchanged, but it is a different program with a few extra and a few missing features. If you share code between the two, follow these habits:

  • Stay with the common syntax. Octave accepts # comments, ! for not, ++, +=, printf and double-quoted escape sequences. MATLAB accepts none of these, and it has no += or ++ operators either. Prefer %, ~, x = x + 1, fprintf and single-quoted strings.
  • Close blocks with plain end. Octave also accepts endif, endfor, endwhile and endfunction, MATLAB does not.
  • Keep functions in files named after the function. Octave allows functions defined in the middle of a script or at the command line, and MATLAB only recently allowed local functions in scripts, at the end of the file.
  • Avoid string objects. MATLAB's double-quoted "text" creates a string object (see Strings and Character Arrays). Octave's double quotes make an ordinary character array, so "a" + "b" behaves differently. Single-quoted character arrays work identically everywhere.
  • Check toolbox dependence. table, readtable, histogram, movmean and many plotting helpers started as MATLAB-only or toolbox features. Octave covers some of them through packages (pkg load statistics, pkg load signal) and misses others. Run ver in either program to see what is installed.
  • Test on both. The only reliable compatibility check is running the file in each program.

A few differences are deliberate extras in Octave: it allows printf, x += 1, x++, functions defined at the command line, and the unwind_protect block. These are fine in Octave-only code, but remember they are not portable.

Features only one side has

MATLAB only (or MATLAB first): Simulink, the live editor (.mlx), App Designer, table/timetable/datetime types in full, string arrays with + concatenation, the arguments block for validating inputs, most toolboxes (Deep Learning, Optimization, Statistics and Machine Learning, Signal Processing), parfor with the Parallel Computing Toolbox, and the Symbolic Math Toolbox with its rich syms interface.

Octave only: being free and open-source, running on a server without a license, the command-line pkg system, printf and puts, comments with #, blocks closed with endif, x += 1 and x++, the unwind_protect construct and a documentation viewer built into the terminal.

Python (NumPy, SciPy, matplotlib, pandas): a general-purpose language, so the same code can read files, call web services, run a web server and train models. Vast package ecosystem (pip), free, but numerical code in Python needs imports for everything and lacks MATLAB's integrated desktop (though Jupyter and Spyder come close).

Translating MATLAB to NumPy: a worked example

Take a small MATLAB function and translate it line by line. It computes the moving average of a vector and returns the positions of the values above their own local average:

MATLAB
function [avg, above] = local_average(x, w)
    k = ones(1, w) / w;
    avg = conv(x, k, 'same');
    above = find(x > avg);
end

The Python version has the same shape, but you adapt the indexing and add one to the result if you want MATLAB's 1-based positions. Beyond indexing, notice that def replaces function, that there is no end (indentation marks the body), that multiple return values become a tuple, and that array functions come from the np namespace.

Python The same function in NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note that conv(..., 'same') pads with zeros, so the first and last values of avg are pulled down in both languages; if you want shrinking windows at the edges, use movmean in MATLAB or divide by a convolved vector of ones, as in Project: Denoise a Signal.

Copy semantics and other quiet differences

  • Assignment. In MATLAB B = A gives you an independent copy (it uses copy-on-write, so it is cheap until you change one). In NumPy B = A makes a second name for the same array; changes through one name appear in the other. Use B = A.copy(). Slices are the same: a NumPy slice is a view, a MATLAB slice is a copy.
  • Vectors. MATLAB has no true 1-D arrays: a vector is 1-by-n or n-by-1. NumPy has genuine 1-D arrays with shape (n,), which print and broadcast differently from a 1-by-n matrix.
  • Integer division and types. uint8(200) + uint8(100) saturates at 255 in MATLAB (see Numeric Types and Precision), while NumPy integers wrap around silently.
  • Truthiness. An if on an array in MATLAB means "all elements nonzero". In Python, if arr: on an array raises an error for more than one element.
  • Printing. MATLAB shows the value of any statement without a semicolon, Python needs print.
Python Copy versus view, saturate versus wrap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Choosing a tool

Pick MATLAB when your team already uses it, you need Simulink or a specific toolbox, or your organization needs vendor support. Pick Octave to run or teach MATLAB-style code without a license, or to execute simple scripts on a server. Pick Python when the numerical work is part of a larger program, for machine learning, or when you need a tool that is free everywhere. Learning one makes the other two much easier, because the underlying ideas (arrays, vectorization, linear algebra, plots) are the same.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line is the NumPy equivalent of the MATLAB matrix product A*B?

    In NumPy, * is element-wise. The matrix product is @ (or np.matmul), which is the reverse of MATLAB's convention.
  2. 2. MATLAB's x(2:4) corresponds to which Python slice?

    MATLAB starts at 1 and includes both ends, so elements 2 to 4 are Python positions 1, 2 and 3, written x[1:4] because the end is excluded.
  3. 3. Which habit makes code portable between MATLAB and Octave?

    Octave accepts the MATLAB spellings, but MATLAB rejects Octave's extras such as # comments, endif, printf and ++.
  4. 4. After B = A in NumPy and then B[0] = 99, what happens to A?

    NumPy assignment does not copy. Use A.copy() to get the independent copy that MATLAB's B = A would give you.
  5. 5. Why does reshape(1:6, 2, 3) need order="F" in NumPy to match MATLAB?

    MATLAB is column-major and NumPy is row-major by default. order="F" (Fortran order) asks NumPy to fill columns first.

Summary

  • The three big differences are 1-based inclusive indexing versus 0-based half-open slices, * versus @ for the matrix product, and column-major versus row-major order.
  • Portable MATLAB/Octave code uses %, ~, plain end, fprintf and single-quoted strings; test it in both programs.
  • Each tool has exclusive features: Simulink and toolboxes (MATLAB), free server use and extra syntax (Octave), general programming and a huge ecosystem (Python).
  • NumPy assignment shares memory (.copy() for independence), integer arithmetic wraps instead of saturating, and 1-D arrays have no row or column orientation.
  • A translation table plus careful attention to indexing covers most conversions.

Next, collect the classic traps in one place with Common Mistakes and How to Fix Them.