Week 6: Introduction to Matlab

An introduction to Matlab by Dr. Yi-Xin Liu at Fudan University (lyx@fudan.edu.cn).

This is a part of the course: Road to Scientific Research: Powerful Computer Applications (XDSY118019.01).

Lecture date: 2026.10.22

What is Matlab?

Installation

Getting started with Matlab

For more: MATLAB for New Users.

Learn the essentials of Matlab

Command Window and Workspace

The Command Window runs expressions. The Workspace remembers variables.

MATLAB

radius = 2;
diameter = 2 * radius;
whos  % radius and diameter are stored

Ask MATLAB for Help

MATLAB

help linspace  % displays syntax, description, and examples

Use doc linspace when you want the full documentation page.

Run Commands in Sequence

MATLAB

x = 3;
y = x + 2;
z = y*y  % z = 25

Assignment and Display

MATLAB

a = 3;     % semicolon suppresses display
b = 4      % b = 4
a + b      % 7

Python

a = 3
b = 4      # no automatic display
a + b      # 7 in a notebook cell

Scalar Power

MATLAB

base = 2;
exponent = 3;
base^exponent  % 8

Python

base = 2
exponent = 3
base**exponent  # 8

A Complete if Block

MATLAB

n = -3;
if n >= 0
    disp("nonnegative")
else
    disp("negative")  % prints negative
end

Python

n = -3
if n >= 0:
    print("nonnegative")
else:
    print("negative")  # prints negative

A for Loop Includes Its Endpoint

MATLAB

for i = 1:5
    disp(i)  % prints 1, 2, 3, 4, 5
end

Python

for i in range(1, 6):
    print(i)  # prints 1, 2, 3, 4, 5

Functions: Input → Output

MATLAB

x = 81;
y = sqrt(x);
y  % 9

Python

import math
x = 81
y = math.sqrt(x)
y  # 9.0

Anonymous Functions

MATLAB

f = @(x) x + 1;
result = f(5);
result  % 6

Python

f = lambda x: x + 1
result = f(5)
result  # 6

Exercise — Sum 1 to 100

Write a for loop that accumulates .

MATLAB

total = 0;
for i = 1:100
    total = total + i;
end
total  % 5050

Python

total = 0
for i in range(1, 101):
    total = total + i
total  # 5050

Create a Numeric Array

MATLAB

v = [1 2 3];
v       % 1-by-3 row vector

Python

import numpy as np
v = np.array([1, 2, 3])
v  # array([1, 2, 3])

Row or Column?

MATLAB

row = [1 2 3];
column = [1; 2; 3];
[size(row); size(column)]  % [1 3; 3 1]

Python

import numpy as np
v = np.array([1, 2, 3])
v.shape  # (3,): neither row nor column

Evenly Spaced Points

MATLAB

x = linspace(0, 1, 6);
x  % 0  0.2  0.4  0.6  0.8  1.0

Python

import numpy as np
x = np.linspace(0, 1, 6)
x  # array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])

Indexing Starts at 1

MATLAB

v = [10 20 30];
first = v(1);
first  % 10

Python

import numpy as np
v = np.array([10, 20, 30])
first = v[0]
first  # 10

The Last Element: end

MATLAB

v = [10 20 30 40];
last = v(end);
last  % 40

Python

import numpy as np
v = np.array([10, 20, 30, 40])
last = v[-1]
last  # 40

Slices Use Inclusive Endpoints

MATLAB

v = [10 20 30 40 50];
middle = v(2:4);
middle  % 20  30  40

Python

import numpy as np
v = np.array([10, 20, 30, 40, 50])
middle = v[1:4]
middle  # array([20, 30, 40])

Two-Dimensional Indexing

MATLAB

A = [1 2 3; 4 5 6];
secondRow = A(2, :)    % [4 5 6]
thirdColumn = A(:, 3)  % [3; 6]

Python

import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6]])
second_row = A[1, :]    # array([4, 5, 6])
third_column = A[:, 2]  # array([3, 6])

Logical Filtering

MATLAB

v = [1 5 2 8 3];
selected = v(v > 3);
selected  % 5  8

Python

import numpy as np
v = np.array([1, 5, 2, 8, 3])
selected = v[v > 3]
selected  # array([5, 8])

Exercise — Extract and Filter

Extract column 2, then keep values greater than 6.

MATLAB

A = [1 4 7 10; 2 5 8 11; 3 9 6 12];
column = A(:, 2);
selected = column(column > 6);
selected  % 9

Python

import numpy as np
A = np.array([[1,4,7,10], [2,5,8,11], [3,9,6,12]])
column = A[:, 1]
selected = column[column > 6]
selected  # array([9])

Element-Wise Array Operations

MATLAB

x = [1 2 4]; y = [2 4 8];
products = x .* y  % 2  8  32
ratios = y ./ x    % 2  2  2
powers = x .^ 2    % 1  4  16

Python

import numpy as np
x = np.array([1,2,4]); y = np.array([2,4,8])
products = x * y  # [2, 8, 32]
ratios = y / x    # [2., 2., 2.]
powers = x ** 2   # [1, 4, 16]

Matrix Multiplication

MATLAB

A = [1 2; 3 4];
B = [2 0; 1 2];
C = A * B;
C  % [4 4; 10 8]

Python

import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([[2,0], [1,2]])
C = A @ B
C  # array([[4,4], [10,8]])

Mathematical Functions on Arrays

MATLAB

x = [0 pi/2 pi];
exponential = exp(x)  % 1.0000  4.8105  23.1407
wave = sin(x)         % 0  1.0000  0 (roundoff possible)

Python

import numpy as np
x = np.array([0, np.pi/2, np.pi])
exponential = np.exp(x)  # shape (3,)
wave = np.sin(x)         # shape (3,)

mean Has a Different Default

MATLAB

A = [1 2 3; 4 5 6];
columnMeans = mean(A)     % [2.5 3.5 4.5]
allMean = mean(A, "all")  % 3.5

Python

import numpy as np
A = np.array([[1,2,3], [4,5,6]])
all_mean = np.mean(A)
all_mean  # 3.5: mean of all elements

Solve a Linear System

MATLAB

A = [1 0 -1; 4 1 1; 3 2 -5];
b = [1; 2; 3];
x = A \ b;
x  % [0.6667; -0.3333; -0.3333]

Python

import numpy as np
A = np.array([[1,0,-1], [4,1,1], [3,2,-5]])
b = np.array([1,2,3])
x = np.linalg.solve(A, b)
x  # [0.6667, -0.3333, -0.3333]

Check the Residual

MATLAB

A = [1 0 -1; 4 1 1; 3 2 -5];
b = [1; 2; 3];
x = A \ b;
residual = norm(A*x - b)  % near machine precision

Python

import numpy as np
A = np.array([[1,0,-1], [4,1,1], [3,2,-5]])
b = np.array([1,2,3])
x = np.linalg.solve(A, b)
residual = np.linalg.norm(A @ x - b)  # near zero

Plot a Curve

MATLAB

x = linspace(0, 2*pi, 200);
y = sin(x);
plot(x, y, "LineWidth", 2)
grid on  % figure: a smooth sine curve

Python

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 200)
plt.plot(x, np.sin(x))

Label the Meaning

MATLAB

x = linspace(0, 2*pi, 200);
plot(x, sin(x), "LineWidth", 2)
xlabel("x"); ylabel("y");
legend("sin(x)", "Location", "best"); grid on

Python

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 200)
plt.plot(x, np.sin(x))
plt.xlabel("x"); plt.legend(["sin(x)"])

Exercise — Build a Computed Curve

On 200 points from 0 to , compute , then plot and label it.

MATLAB

x = linspace(0, 2*pi, 200);
y = exp(-x) .* sin(x);
plot(x,y,"LineWidth",2); xlabel("x"); ylabel("y");
legend("exp(-x) sin(x)"); grid on  % damped sine curve

Python

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 200)
y = np.exp(-x) * np.sin(x)
plt.plot(x,y); plt.xlabel("x"); plt.legend(["exp(-x) sin(x)"])

Polynomial Coefficient Order

Both forms represent .

MATLAB

coefficients = [3 2 1];  % descending powers
x = 2;
p = polyval(coefficients, x);
p  % p = 17

Python

from numpy.polynomial import Polynomial
p = Polynomial([1, 2, 3])  # ascending powers
p(2)  # 17.0

Find a Nonlinear Root

Find a root of in [0,1].

MATLAB

f = @(x) x.^2 - exp(-x);
endpointValues = [f(0) f(1)];  % [-1.0000 0.6321]
r = fzero(f, [0 1]);
[r, f(r)]  % approximately [0.7035 0]

Python

import numpy as np
from scipy.optimize import root_scalar
f = lambda x: x**2 - np.exp(-x)
r = root_scalar(f, bracket=[0,1]).root
r, f(r)  # approximately (0.7035, 0)

Numerical Integration

Compute .

MATLAB

f = @(x) x.^2 .* exp(-2*x);
value = integral(f, 0, 2);
exact = (1 - 13*exp(-4))/4;
[value, exact]  % approximately [0.1905 0.1905]

Python

import numpy as np
from scipy.integrate import quad
f = lambda x: x**2 * np.exp(-2*x)
value, error = quad(f, 0, 2)
value, error  # approximately (0.1905, 2.1e-15)

Exit Ticket — * or .*?

Choose the operator for matrix and element-wise products.

MATLAB

A = [1 2; 3 4]; B = [2 0; 1 2];
u = [1 2 3]; v = [4 5 6];
A * B    % [4 4; 10 8]
u .* v   % [4 10 18]

Python

import numpy as np
A=np.array([[1,2],[3,4]]); B=np.array([[2,0],[1,2]])
u=np.array([1,2,3]); v=np.array([4,5,6])
A @ B   # matrix multiplication
u * v   # element-wise multiplication

Demo

Go to:

while: Repeat Until False (Optional)

MATLAB

i = 1;
while i < 4
    disp(i^2)  % prints 1, 4, 9
    i = i + 1;
end

Python

i = 1
while i < 4:
    print(i**2)  # prints 1, 4, 9
    i = i + 1

zeros: Allocate a Shape (Optional)

MATLAB

A = zeros(2, 3);
A  % 2-by-3 array filled with 0

Python

import numpy as np
A = np.zeros((2, 3))
A  # shape (2, 3), filled with 0

ones: Constant Starting Values (Optional)

MATLAB

A = ones(2, 3);
A  % 2-by-3 array filled with 1

Python

import numpy as np
A = np.ones((2, 3))
A  # shape (2, 3), filled with 1

eye: Identity Matrix (Optional)

MATLAB

I = eye(3);
A = [1 2 3; 4 5 6; 7 8 9];
A * I  % unchanged: [1 2 3; 4 5 6; 7 8 9]

Python

import numpy as np
I = np.eye(3)
A = np.array([[1,2,3], [4,5,6], [7,8,9]])
A @ I  # unchanged, displayed as floats

reshape: Column-Major Order (Optional)

MATLAB

v = 1:6;
A = reshape(v, 2, 3);
A  % [1 3 5; 2 4 6]

Python

import numpy as np
v = np.arange(1, 7)
A = np.reshape(v, (2, 3))
A  # [[1,2,3], [4,5,6]]: row-major default

Transpose: .' versus ' (Optional)

MATLAB

z = [1+2i 3-4i];
plainTranspose = z.'      % [1+2i; 3-4i]
conjugateTranspose = z'   % [1-2i; 3+4i]

Python

import numpy as np
z = np.array([[1+2j, 3-4j]])
z.T  # [[1+2j], [3-4j]]

Standard Deviation Defaults (Optional)

MATLAB

v = [1 2 3];
sampleStd = std(v)       % 1.0000
populationStd = std(v,1) % 0.8165

Python

import numpy as np
v = np.array([1, 2, 3])
np.std(v)  # 0.8165: population normalization

Polynomial Roots (Optional)

MATLAB

coefficients = [1 -3 2];
r = roots(coefficients);
r  % [2; 1]

Python

from numpy.polynomial import Polynomial
p = Polynomial([2, -3, 1])
p.roots()  # array([1., 2.])

Linear Interpolation (Optional)

MATLAB

x = [0 1 2 3];
y = [0 1 4 9];
xq = 1.5;
yq = interp1(x, y, xq, "linear");
[xq, yq]  % [1.5 2.5]

Python

import numpy as np
from scipy.interpolate import interp1d
x=np.array([0,1,2,3]); y=np.array([0,1,4,9])
f = interp1d(x, y, "linear")
f(1.5)  # 2.5

Bounded Scalar Optimization (Optional)

MATLAB

f = @(x) exp(-x.^2) .* cos(2*x);
[xmin, fmin] = fminbnd(f, 0, 2);
[xmin, fmin]  % approximately [1.1445 -0.1776]

Python

import numpy as np
from scipy.optimize import minimize_scalar
f = lambda x: np.exp(-x**2) * np.cos(2*x)
res = minimize_scalar(f, bracket=[0,2])  # search seeds, not bounds
res.x, f(res.x)  # approximately (1.1445, -0.1776)

Linear Fit Coefficients (Optional)

MATLAB

x = [0 1 2 3];
y = [1 3 5 7];
coefficients = polyfit(x, y, 1);
coefficients  % [2 1]: slope, intercept

Python

from scipy.stats import linregress
x=[0,1,2,3]; y=[1,3,5,7]
fit = linregress(x, y)
fit.slope, fit.intercept  # (2.0, 1.0)

ode45: Time Down Rows (Optional)

MATLAB

k = 1; r = 0.2; u0 = 0.8;
rhs = @(t,u) k*u - r*u.^2;
[t,u] = ode45(rhs, [0 8], u0);
size(t), size(u)  % both N-by-1: time down rows

Python

import numpy as np
from scipy.integrate import solve_ivp
k=1; r=0.2; u0=0.8
rhs = lambda t,u: k*u-r*u**2
sol = solve_ivp(rhs, [0,8], [u0], dense_output=True)
t = np.linspace(0,8,50); u = sol.sol(t)
t.shape, u.shape  # (50,), (1,50): states down rows

Save Tested Commands as a .m Script (Optional)

After commands work, copy them into a script and save, for example, as damped_sine.m.

MATLAB

x = linspace(0, 2*pi, 200);
y = exp(-x) .* sin(x);
plot(x, y, "LineWidth", 2)
xlabel("x"); ylabel("y"); grid on