TExcelTAD
Home › MATLAB / Octave › MATLAB vs Python

MATLAB vs Python

Python with NumPy (arrays), SciPy (numerical methods), Matplotlib (plots) and pandas (tables) covers much of what MATLAB does, and many teams use both. The concepts carry over directly (arrays, element-wise operations, vectorisation, logical masks), but the details differ in ways that cause classic bugs: counting from 0, half-open slices, row-major storage and views that share memory. This lesson puts the two side by side. The MATLAB examples run here; the Python equivalents are shown next to them, and the NumPy and Python courses teach that side properly.

The quick translation table

Task MATLAB Python / NumPy (import numpy as np)
First element v(1) v[0]
Last element v(end) v[-1]
Elements 2 to 4 v(2:4) (inclusive) v[1:4] (end excluded)
Every second v(1:2:end) v[::2]
Range 1..5 1:5 np.arange(1, 6)
Evenly spaced linspace(0, 1, 5) np.linspace(0, 1, 5)
Zeros zeros(3) is 3x3 np.zeros(3) is a 1-D array of 3
Size size(A), numel(A) A.shape, A.size
Matrix product A * B A @ B
Element-wise product A .* B A * B
Power A .^ 2 A ** 2
Transpose A.' (A' also conjugates) A.T
Solve A x = b A \ b np.linalg.solve(A, b)
Column sums sum(A) A.sum(axis=0)
Sum of everything sum(A(:)) or sum(A, 'all') A.sum()
Logical mask v(v > 2) v[v > 2]
Indices of true find(v > 2) (1-based) np.nonzero(v > 2)[0] (0-based)
Max and its position [m, i] = max(v) m, i = v.max(), v.argmax()
Reshape reshape(v, 2, 3) (column-major) v.reshape(2, 3) (row-major)
Copy B = A (always a copy) B = A.copy() (B = A shares!)
Anonymous function f = @(x) x.^2 f = lambda x: x ** 2
Text 'abc', "abc" 'abc', "abc" (same type)
Containers cell array, struct list, dict
Print formatted fprintf('%d\n', n) print(f"{n}")
Comment % ... # ...

Indexing: 1-based and inclusive vs 0-based and half-open

MATLAB counts from 1 and a range a:b includes both ends. Python counts from 0 and a slice a:b stops before b, so the number of elements is b - a:

matlab · try it yourself
v = 10:10:60;
fprintf('first %d, last %d\n', v(1), v(end));
disp(v(2:4))          % elements 2, 3, 4
disp(v(end-1:end))    % the last two
disp(v(1:2:end))      % every second element
first 10, last 60
   20   30   40
   50   60
   10   30   50
python · try it yourself
import numpy as np
v = np.arange(10, 70, 10)
print("first", v[0], "last", v[-1])
print(v[1:4])     # elements at positions 1, 2, 3
print(v[-2:])     # the last two
print(v[::2])     # every second element
first 10 last 60
[20 30 40]
[50 60]
[10 30 50]

Shapes: everything is a matrix vs true 1-D arrays

In MATLAB every array has at least two dimensions: a vector is a 1xN row or an Nx1 column, and zeros(3) makes a 3x3 matrix. NumPy has genuine 1-D arrays with shape (3,), neither row nor column, and np.zeros(3) makes one of those.

Memory order matters for reshape. MATLAB stores arrays column by column (column-major, like Fortran) and fills reshaped arrays down the columns; NumPy defaults to row by row (row-major, like C):

matlab · try it yourself
z = zeros(3);
fprintf('zeros(3) is %dx%d\n', size(z));
M = reshape(1:6, 2, 3)          % fills down the columns
R = reshape(1:6, 3, 2)'         % row-by-row, like NumPy's default
zeros(3) is 3x3
M =

   1   3   5
   2   4   6

R =

   1   2   3
   4   5   6
python · try it yourself
import numpy as np
print(np.zeros(3).shape)
print(np.arange(1, 7).reshape(2, 3))             # row-major (C order)
print(np.arange(1, 7).reshape(2, 3, order="F"))  # column-major, like MATLAB
(3,)
[[1 2 3]
 [4 5 6]]
[[1 3 5]
 [2 4 6]]

When you port code that reshapes or flattens (A(:) vs A.ravel()), check the order, or the numbers end up in the wrong places without any error.

Operators: * means different things

In MATLAB, * is the matrix product and the dotted operators .*, ./, .^ work element by element. In NumPy it is the other way round: * is element-wise and @ is the matrix product. Both expand singleton dimensions automatically (MATLAB calls it implicit expansion, NumPy broadcasting), so a column plus a row gives a matrix:

matlab · try it yourself
A = [1 2; 3 4];
B = [10 20; 30 40];
matrixProduct = A * B
elementwise = A .* B
grid = [1; 2; 3] + [10 20]      % 3x1 plus 1x2 expands to 3x2
matrixProduct =

    70   100
   150   220

elementwise =

    10    40
    90   160

grid =

   11   21
   12   22
   13   23
python · try it yourself
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[10, 20], [30, 40]])
print(A @ B)       # matrix product
print(A * B)       # element-wise
print(np.array([[1], [2], [3]]) + np.array([10, 20]))
[[ 70 100]
 [150 220]]
[[ 10  40]
 [ 90 160]]
[[11 21]
 [12 22]
 [13 23]]

Reductions: columns by default vs everything by default

MATLAB functions such as sum, mean and max work down the columns of a matrix by default (dimension 1). NumPy's work on the whole array unless you give an axis (and axis=0 is MATLAB's dimension 1):

matlab · try it yourself
A = [1 2; 3 4];
disp(sum(A))         % column sums
disp(sum(A, 2)')     % row sums
disp(sum(A(:)))      % everything
[m, i] = max([4 9 2 9]);
fprintf('max %d at position %d (the first one)\n', m, i);
   4   6
   3   7
10
max 9 at position 2 (the first one)

In NumPy the same results are A.sum(axis=0), A.sum(axis=1), A.sum(), and np.argmax([4, 9, 2, 9]) returns 1, the 0-based position.

Copies vs views

MATLAB variables behave like values: B = A gives you an independent copy (MATLAB only copies the data when one of them changes, so it's cheap). In Python, B = A makes a second name for the same array, and a NumPy slice is a view into the original memory:

matlab · try it yourself
A = [1 2 3 4];
B = A;           B(1) = 99;       % changes only B
C = A(2:3);      C(1) = -1;       % a slice is a copy too
fprintf('A = %s, B = %s, C = %s\n', mat2str(A), mat2str(B), mat2str(C));
A = [1 2 3 4], B = [99 2 3 4], C = [-1 3]
python · try it yourself
import numpy as np
A = np.array([1, 2, 3, 4])
B = A;           B[0] = 99    # same array!
C = A[1:3];      C[0] = -1    # a view into A
print("A =", A)
D = A.copy();    D[0] = 0     # an independent copy
print("A =", A, "D =", D)
A = [99 -1  3  4]
A = [99 -1  3  4] D = [ 0 -1  3  4]

The exception in MATLAB is handle classes (see Handle Classes & Events), which have reference semantics like Python objects.

Calling one from the other

The two worlds can also call each other.

Python from MATLAB. MATLAB runs a Python interpreter in-process; prefix any Python module with py.. Python lists, dicts and NumPy arrays are converted to and from MATLAB types (MATLAB-only, Octave has no py. interface):

matlab
pyenv                                   % which Python MATLAB uses
r = py.math.sqrt(16)                    % call a Python function
words = py.str('a,b,c').split(',');     % Python methods work too
x = double(py.numpy.linspace(0, 1, 5))  % NumPy array -> MATLAB double
total = double(pyrun("t = sum(range(n))", "t", n=10))   % run a snippet (R2021b+)

MATLAB output:

text
r =
     4
x =
         0    0.2500    0.5000    0.7500    1.0000
total =
    45

MATLAB from Python. The MATLAB Engine API for Python (pip install matlabengine, needs a MATLAB installation) starts MATLAB from a Python program:

python
import matlab.engine
eng = matlab.engine.start_matlab()
print(eng.sqrt(16.0))                     # 4.0
print(eng.eval("magic(3)", nargout=1))    # a matlab.double array
eng.quit()

For Octave, the Python package oct2py does the same job (from oct2py import octave; octave.eval("x = magic(3)")).

When to use which

Prefer MATLAB when... Prefer Python when...
you need Simulink, specialised toolboxes or certified workflows you want free tools and a huge open-source ecosystem
your team, course or industry already standardises on it you combine numerics with web services, databases or ML frameworks
you want one integrated, well-documented environment you deploy to servers and containers without licences
you write a lot of linear algebra in compact notation you need general-purpose programming beyond numerics

Knowing both is common. Translate carefully at the boundaries: indices, slice ends, reshape order and copies.

Learn more: NumPy, Python, pandas, MATLAB vs Octave, Indexing.

Test yourself

Which NumPy expression selects the same elements as MATLAB's v(2:4)?

  1. v[2:4]
  2. v[1:4]
  3. v[1:3]
  4. v[2:5]

What does reshape(1:6, 2, 3) give in MATLAB?

  1. [1 2 3; 4 5 6]
  2. [1 3 5; 2 4 6]
  3. [1 4; 2 5; 3 6]
  4. An error

In NumPy, A * B on two 2x2 arrays computes...

  1. The matrix product, like MATLAB's A * B
  2. The element-wise product, like MATLAB's A .* B
  3. The dot product of the first rows
  4. An error