Tutorial · Beginner · 10 min
Vectors, matrices and indexing
Everything in MathLab is a matrix. Learn to build them, combine them and pick out exactly the elements you need.
Rows, columns and ranges
Spaces or commas separate elements; semicolons start a new row.
a:bcounts in steps of 1,a:step:bin other steps.
Try it ↗row = [1 2 3] col = [1; 2; 3] r = 0:0.25:1row = 1×3 1 2 3 col = 3×1 1 2 3 r = 1×5 0 0.25 0.5 0.75 1Matrices and their size
A matrix is rows separated by semicolons.
sizegives rows × columns, andA'is the transpose.
Try it ↗A = [1 2 3; 4 5 6] size(A) A'A = 2×3 1 2 3 4 5 6 ans = 1×2 2 3 ans = 3×2 1 4 2 5 3 6
Element-wise or matrix maths?
*is matrix multiplication;.*,./and.^work element by element. Most plotting code needs the dotted versions:x.^2, notx^2.
Try it ↗x = [1 2 3]; x .* x % element-wise: [1 4 9] x * x' % matrix product: 1 + 4 + 9 = 14 x.^2ans = 1×3 1 4 9 ans = 14 ans = 1×3 1 4 9
Tip: Getting "Inner matrix dimensions must agree"? You probably meant .* instead of *.
Picking elements
Indices start at 1.
endmeans the last one,:means all. A condition likex > 0gives a mask that selects matching elements.
Try it ↗A = magic(4) A(2, 3) % row 2, column 3 A(:, 1)' % the first column, as a row A(end, :) % the last row v = -3:3; v(v > 0) % only the positive valuesA = 4×4 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 ans = 10 ans = 1×4 16 5 9 4 ans = 1×4 4 14 15 1 ans = 1×3 1 2 3
Solving a linear system
To solve A x = b, use
A \ b. It is faster and more accurate than computinginv(A).
Try it ↗A = [4 -2 1; -2 4 -2; 1 -2 4]; b = [11; -16; 17]; x = A \ b residual = norm(A*x - b)x = 3×1 1 -2 3 residual = 0