Ron Bakker/MathLabHelp
Open MathLab ↗

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.

  1. Rows, columns and ranges

    Spaces or commas separate elements; semicolons start a new row. a:b counts in steps of 1, a:step:b in other steps.

    row = [1 2 3]
    col = [1; 2; 3]
    r = 0:0.25:1
    Try it ↗
    row = 1×3
      1  2  3
    col = 3×1
      1
      2
      3
    r = 1×5
         0  0.25   0.5  0.75     1
  2. Matrices and their size

    A matrix is rows separated by semicolons. size gives rows × columns, and A' is the transpose.

    A = [1 2 3; 4 5 6]
    size(A)
    A'
    Try it ↗
    A = 2×3
      1  2  3
      4  5  6
    ans = 1×2
      2  3
    ans = 3×2
      1  4
      2  5
      3  6
  3. Element-wise or matrix maths?

    * is matrix multiplication; .*, ./ and .^ work element by element. Most plotting code needs the dotted versions: x.^2, not x^2.

    x = [1 2 3];
    x .* x            % element-wise: [1 4 9]
    x * x'            % matrix product: 1 + 4 + 9 = 14
    x.^2
    Try it ↗
    ans = 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 *.

  4. Picking elements

    Indices start at 1. end means the last one, : means all. A condition like x > 0 gives a mask that selects matching elements.

    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 values
    Try it ↗
    A = 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
  5. Solving a linear system

    To solve A x = b, use A \ b. It is faster and more accurate than computing inv(A).

    A = [4 -2 1; -2 4 -2; 1 -2 4];
    b = [11; -16; 17];
    x = A \ b
    residual = norm(A*x - b)
    Try it ↗
    x = 3×1
       1
      -2
       3
    residual = 0