Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 45 ยท Matrices and Arrays

Ranges and Special Matrices

Create vectors and matrices fast in MATLAB and Octave: the colon operator, linspace, logspace, zeros, ones, eye, diag, rand, randi, magic, repmat and meshgrid.

Typing every element of a matrix by hand works for a few numbers, but real programs need a thousand points between 0 and 1, a 100-by-100 block of zeros to fill in later, or a grid of coordinates for a plot. MATLAB and Octave have short, memorable tools for all of these. Learning them early saves you from loops you would otherwise write.

This lesson covers the colon operator and linspace for sequences, the matrix builders zeros, ones, eye, diag and magic, random numbers, repmat for tiling and meshgrid for coordinate grids. Real MATLAB/Octave code is read-only; the NumPy stand-ins reproduce the numbers. If you need to refresh how matrices and size work, see Everything Is a Matrix.

Make a sequence

a:step:b Colon operator. The end point is included.
linspace You choose how many points.
logspace Points spaced by powers of ten.
1 / 2

The colon operator

start:stop creates a row vector counting by 1. start:step:stop uses the step you give. The stop value is included when the step lands on it exactly, which is the opposite of Python's range.

MATLAB
>> 1:5
ans =

     1     2     3     4     5

>> 0:0.25:1
ans =

         0    0.2500    0.5000    0.7500    1.0000

>> 10:-3:0
ans =

    10     7     4     1

Negative steps count down. If the step points the wrong way (5:1) the result is an empty array, 1x0, not an error. The colon operator is also used inside indexes, but that is the next lesson.

Be careful with fractional steps: 0:0.1:1 gives 11 values, but floating-point rounding makes this fragile in other languages. MATLAB takes care of the end point for you, while NumPy's arange does not. When you care about the number of points, use linspace.

linspace and logspace

linspace(a, b, n) returns n evenly spaced points from a to b, both ends included. If you leave out n, you get 100 points.

MATLAB
>> linspace(0, 1, 5)
ans =

         0    0.2500    0.5000    0.7500    1.0000

logspace(a, b, n) returns n points from 10^a to 10^b, evenly spaced on a log scale.

MATLAB
>> logspace(0, 3, 4)
ans =

           1          10         100        1000

These two are what you use for the x-axis of a plot, or for sweeping a parameter over a range.

The stand-in below reproduces these sequences. It has a helper colon(a, step, b) that includes the end point like MATLAB, since np.arange stops before it.

Python Ranges, linspace and logspace (stand-in)

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.

Building matrices of a given shape

MATLAB Result
zeros(m, n) m-by-n matrix of zeros
ones(m, n) m-by-n matrix of ones
eye(n) n-by-n identity matrix
diag(v) square matrix with vector v on the diagonal
diag(A) the diagonal of matrix A as a column
zeros(n) an n-by-n square, using one argument
MATLAB
>> zeros(2, 3)
ans =

     0     0     0
     0     0     0

>> eye(3)
ans =

     1     0     0
     0     1     0
     0     0     1

>> diag([4 5 6])
ans =

     4     0     0
     0     5     0
     0     0     6

zeros is the standard way to preallocate: create the result array at its final size, then fill it in a loop. That is much faster than growing it one element at a time, as Performance and Memory explains. To make an array the same shape as another, use zeros(size(A)).

The most common bug here is a single argument. zeros(3) is a 3-by-3 matrix, not a vector of three zeros. For a 3-element column use zeros(3, 1).

Python zeros, ones, eye and diag (stand-in)

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.

Random numbers

Three generators cover most needs:

  • rand(m, n) gives uniformly distributed numbers between 0 and 1.
  • randn(m, n) gives normally distributed numbers with mean 0 and standard deviation 1.
  • randi(k, m, n) gives random integers from 1 to k; randi([a b], m, n) uses the range a to b.
MATLAB
>> rand(2, 3)       % different on every run
>> randi(6, 1, 5)   % five dice rolls

To get the same numbers on every run, seed the generator first with rng(1) in MATLAB (or rand('seed', 1) style calls in older Octave). The sequences that MATLAB, Octave and NumPy produce for the same seed are not the same, so never compare numbers across programs. Random numbers are covered in depth in Statistics and Random Numbers.

magic and repmat

magic(n) returns an n-by-n magic square, where all rows, columns and the main diagonals add up to the same number. It is a convenient test matrix.

MATLAB
>> magic(3)
ans =

     8     1     6
     3     5     7
     4     9     2

repmat(A, m, n) tiles A into an m-by-n grid of copies.

MATLAB
>> repmat([1 2], 2, 3)
ans =

     1     2     1     2     1     2
     1     2     1     2     1     2

NumPy has no magic, so the stand-in below hard-codes the 3-by-3 square and checks that every row and column sums to 15. np.tile is the counterpart of repmat.

Python A magic square and repmat (stand-in)

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.

meshgrid: coordinates for every point

To evaluate a function of two variables over a grid, you need the x-coordinate and y-coordinate of every grid point. [X, Y] = meshgrid(x, y) builds two matrices for you: X repeats x along each row and Y repeats y down each column.

MATLAB
>> [X, Y] = meshgrid(1:3, 1:2)
X =

     1     2     3
     1     2     3

Y =

     1     1     1
     2     2     2

With these, any formula over the grid is just arithmetic: Z = X.^2 + Y.^2. Surface and contour plots, covered in 3-D Plots, Surfaces and Contours, start from exactly this. NumPy's np.meshgrid works the same way with its default settings.

Python meshgrid and a formula over a grid (stand-in)

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.

Tip: Rows of the grid follow y, columns follow x. That is why meshgrid(1:3, 1:2) returns 2-by-3 matrices even though the x-vector is listed first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many elements does 0:2:10 contain?

    The values are 0, 2, 4, 6, 8 and 10. The colon operator includes the stop value when the step lands on it.
  2. 2. What does zeros(3) create?

    With one argument, zeros makes a square matrix. For a column of three zeros write zeros(3, 1).
  3. 3. Which call returns 4 evenly spaced points from 0 to 1, including both ends?

    linspace(a, b, n) always returns n points including both ends. Here the values are 0, 1/3, 2/3 and 1.
  4. 4. What is the size of X after [X, Y] = meshgrid(1:4, 1:3)?

    Rows correspond to the y vector (3 values) and columns to the x vector (4 values), so the matrices are 3 by 4.

Summary

  • a:step:b includes the end point when it lands on it; wrong-direction steps give an empty array.
  • linspace(a, b, n) sets the number of points; logspace spaces points by powers of ten.
  • zeros, ones, eye and diag build standard matrices; zeros(n) is n-by-n, not a vector.
  • rand, randn and randi generate random numbers, and seeds do not match across programs.
  • magic makes test matrices, repmat tiles, and meshgrid builds coordinate grids for functions of two variables.

Next, pick out parts of these arrays in Indexing and Slicing.