Skip to main content

Section 1.3 Creating vectors and matrices

A vector in Matlab is an ordered list of numbers. It does not always have a geometric meaning. For example, recording the high temperature on every day of August, we get a vector with 31 components; we do not normally visualize it as an arrow of some length and direction. Matlab distinguishes between row vectors and column vectors, which are defined below.

A matrix is a rectangular array of numbers. For example, a 4×6 matrix has 4 rows and 6 columns. A matrix with one row (for example a 1×6 matrix) is a row vector. A matrix with one column (for example a 4×1 matrix) is a column vector. Thus, vectors in Matlab are just a special kind of matrices.

One can create a row vector by listing its components:

x = [8 6 7 5 3 0 9]

or

x = [8, 6, 7, 5, 3, 0, 9]

Either spaces or columns can be used to separate the entries. To create a column vector, one can either separate the entries by semicolons:

x = [8; 6; 7; 5; 3; 0; 9]

or create a row vector and transpose it by putting an apostrophe at the end:

x = [8 6 7 5 3 0 9]'

To create a matrix one needs both kinds of separators: spaces or colons within each row, and semicolons between the rows. For example,

A = [8 6; 7 5; 3 0]

creates a 3×2 matrix. Its transpose A' is a 2×3 matrix, same as

[8 7 3; 6 5 0]

Regularly-spaced vectors are described by three numbers: first entry, step size, and last entry. For example: 3:2:15 means the same as [3 5 7 9 11 13 15]: the first entry is 3, after that they increase by 2, until reaching 15. The step size can be omitted when it is equal to 1: that is, -1:4 is the same as [-1 0 1 2 3 4].

Zeros and ones are special kinds of matrices and vectors, filled with the same number: 0 or 1. The commands are called zeros and ones. They require two parameters: the number of rows and the number of columns. For example, zeros(2, 2) creates a 2×2 matrix filled with zeros, and ones(1, 5) is a row vector with 5 entries: [1 1 1 1 1]. These are useful as starting points for building matrices and vectors.

Create a vector with numbers 20, 19, 18, ..., 3, 2, 1 in this order.

Answer
v = 20:-1:1

The step size here is -1, so the term after 20 is 20 + (-1) = 19, after that we get 19 + (-1) = 18, and so on until reaching 1.