2.7. Vectors and Matrices in MATLAB

MATLAB (name taken from MATrix LABoratory) is designed to work with variables that contain multiple numeric values. So we can perform calculations on every value in the variable with just one expression and conveniently perform linear algebra calculations. We will put off the linear algebra aspect for now and focus on vectorized equations that can do calculations on many values at once without the need to write a for loop.

The numeric variables that we have used so far have only one value. In math terminology, we call such variables scalars. MATLAB reports that the size of scalars is \(1{\times}1\). We will now introduce vectors and matrices, but focus on vectors. Vectors can also be called arrays, but note that MATLAB has both row vectors and column vectors.

scalar

A scalar is a variable with size \(1{\times}1\). That is, it has only one value.

The isscalar function tests if a variable is a scalar.

row vector

A row vector is a variable of size \(1{\times}n\), where \(n > 1\). It has one row containing \(n\) values.

Row vectors can be created with the colon operator, manually entered, or with one of several MATLAB functions. The isvector function tests if a variable is a vector, while the isrow function more specifically tests if a variable is a row vector.

>> C = 1:6          % C is a 1-by-6 row vector
C =
    1     2     3     4     5     6
>> D = [3 5 7 9]    % D is a 1-by-4 row vector
D =
    3     5     7     9

column vector

A column vector is a variable of size \(m{\times}1\), where \(m > 1\). It has one column containing \(m\) values.

Column vectors can be created with the transpose of a row vector (apostrophe in MATLAB), manually entered, or created with one of several MATLAB functions. The iscolumn function tests if a variable is a column vector. We usually use column vectors to hold geometric points and vectors.

% transpose operator
>> E = (1:4)'
E =
    1
    2
    3
    4
>> F = [3; 5; 7; 9]
F =
    3
    5
    7
    9

Vectors in our physical 3-dimensional world are said to be in \(\mathbb{R}^3\), that is, they consist of three real numbers defining their magnitude in the \(\bm{x}\), \(\bm{y}\), and \(\bm{z}\) directions. Like a piece of paper, vectors on a plane contain two elements and are said to be in \(\mathbb{R}^2\). Vectors may have dimensions higher than 3. Generally, we call this \(\mathbb{R}^n\). For some applications, the coefficients of vectors may also be complex numbers, which are denoted as \(\mathbb{C}^n\).

Row vectors are often used for sequences of numbers. However, when referring to a geometric vector, the term vector usually refers to a column vector. For convenience of notation, the elements of a column vector may be written between parentheses as a row of numbers separated by commas.

These are both column vectors in \(\mathbb{R}^3\).

\[\begin{split}\begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix} = (1, 2, 3)\end{split}\]

matrix

A matrix is a variable of size \(m{\times}n\), where \(m > 1\) and \(n > 1\). It has \(m\) rows and \(n\) columns.

Matrices can be manually entered or created with one of several MATLAB functions. The ismatrix function tests if a variable is a matrix.

Note that the ismatrix function considers vectors (\(m = 1\) or \(n = 1\)) to be matrices; however, we will attempt to distinguish between them since vectors have some unique properties.

Matrices may also be formed by concatenating row vectors or column vectors.

>> G = [1 2 3; 4 5 6; 7 8 9];
>> A = [1 2 4];
>> B = [2 1 6];
>> H = [A; B]
H =
    1     2     4
    2     1     6
>> D = [1; 1; 2];
>> E = [0; 1; 3];
>> J = [D E]
J =
    1     0
    1     1
    2     3

Matrices of different sizes may be combined as long as the resulting matrix is rectangular or square. Figure Fig. 2.5 and the following code sample show how matrices of size \(4{\times}5\), \(4{\times}1\), and \(2{\times}6\) are concatenated with the command D = [[A B]; C] to make a \(6{\times}6\) matrix.

>> A = ones(4, 5)
A =
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1
     1     1     1     1     1
>> B = 2*ones(4, 1)
B =
     2
     2
     2
     2
>> C = 3*ones(2, 6)
C =
     3     3     3     3     3     3
     3     3     3     3     3     3
>> D = [[A B];C]
D =
     1     1     1     1     1     2
     1     1     1     1     1     2
     1     1     1     1     1     2
     1     1     1     1     1     2
     3     3     3     3     3     3
     3     3     3     3     3     3
Matrices concatenated, D = [[A B]; C]

Fig. 2.5 Matrices concatenated, D = [[A B]; C]

Higher dimension data

Data arrays containing more than two dimensions are also possible. Color images have size \(m{\times}n{\times}3\), as they contain three monochrome images for red, green, and blue.

2.7.1. Matrix Generating Functions

One example of when it is desired to create a simple matrix or vector of a pre-determined size is when a loop is used to modify the vector data. For example, consider the following lines of code:

for k=1:5
    A(k) = k;
end

To this code, MATLAB gives a warning that says:

The variable A appears to change size with each loop iteration (within a script). Consider preallocating for speed.

The warning is fixed by first creating (preallocating) the vector as follows:

A = zeros(1,5);
for k=1:5
    A(k) = k;
end

MATLAB has several functions that will create matrices and vectors. The zeros and ones functions create vectors or matrices with either all zero or all one values.

>> A = zeros(1,5)
A =
    0    0    0    0    0
>> B = ones(2)
B =
    1     1
    1     1
>> C = ones(3,1)
C =
    1
    1
    1
>> D = zeros(3,2)
D =
    0     0
    0     0
    0     0

2.7.2. Scalar—Vector Arithmetic

When an arithmetic operation occurs between a scalar and a vector or matrix, the operation is applied to each vector element.

>> A = zeros(1,5)
A =
    0    0    0    0    0
>> A = A + 2
A =
    2    2    2    2    2
>> A = A*3
A =
    6    6    6    6    6
>> A = A/2
A =
    3    3    3    3    3
>> A = A - 1
A =
    2    2    2    2    2

2.7.3. Element-wise Arithmetic

Addition and subtraction arithmetic between vectors and matrices happens as expected as long as the two matrices are the same size.

>> A = 2*ones(1,4)
A =
    2     2     2     2
>> B = ones(1,4)
B =
    1     1     1     1
>> A + B
ans =
    3     3     3     3

When we want to perform multiplication, division, or use an exponent element-wise, that is, between each element of the vectors, we use the .*, ./, and .^ element-wise operators. These operators take two vectors or matrices of the same size and operate on pairs of values at the same position.

>> a = [2 3 4];
>> b = [5 6 7];
>> c = a.*b
c =
    10    18    28
>> c ./ a
ans =
     5     6     7

The element-wise exponent can be used between vectors and between a scalar and a vector.

>> 2.^a
ans =
     4     8    16
>> a.^2
ans =
     4     9    16
>> b.^a
ans =
     25     216    2401

2.7.4. Vector and Matrix Indices

You can select vector elements with parentheses around an index number or range of indices. The range of valid indices for a vector of length N is 1 to N.

MATLAB produces an error when a vector is indexed outside of its range. However, the vector is expanded when an assignment statement adds elements beyond the current range.

>> A = [2 4 6 8];
>> A(1)
ans =
    2
>> A(4)
ans =
    8
>> A(5)
Index exceeds the number of array elements (4).
>> A(5) = 10
A =
    2     4     6     8    10

2.7.4.1. Ranges of Indices

The colon operator can be used to select a subset of a vector. MATLAB keeps a special identifier called end for the last element of a vector. Ranges of indices can be used when reading from a vector and when assigning values to it.

>> A = 1:10;
>> A(1:5)
ans =
    1     2     3     4     5
>> A(6:end) = A(1:5)
A =
    1     2     3     4     5     1     2     3     4     5
>> A(2:2:end-2) = [10 9 8 7]
A =
    1    10     3     9     5     8     2     7     4     5

2.7.4.2. Accessing Data in Matrices

You can extract values from a matrix by indexing the row and column numbers.

>> x = A(rowNum,colNum);

You can use the keyword end to index the last element in a row or a column.

>> x = A(end, end)
x =
    92

The following reads the data value that is in the row before the last row and the column that is two columns before the last column.

>> x = A(end-1,end-2)
x =
    72

To extract an entire row or column from an array, you can use a colon (:). Think of the colon as saying all rows or all columns. The next example stores a column from matrix A in vector x:

>> x = A(:,colNum);

Use a vector containing the desired index values to reference a range of rows or columns. For example, both lines of the following code will extract the first three rows of A.

>> firstThree = A(1:3,:);
>> firstThree = A([1 2 3],:);

What index values will return all four corners of A?

>> x = A([1 end],[1 end])

2.7.5. Delete Vector or Matrix Data

Assigning vector or matrix elements to take values of empty square brackets ([]) deletes them. Selecting the elements to delete can use either array indexing or logical vectors, which are covered in Logical Vectors. The empty square brackets will also create an empty vector.

>> w = []
w =
     []
>> isempty(w)
ans =
  logical
   1
>> v = 1:6
v =
    1.00    2.00    3.00    4.00    5.00    6.00
>> v(2:4) = []
v =
    1.00    5.00    6.00

>> B = randi(20, 1, 5)  % random numbers
B =
   19.00   14.00   16.00   15.00    8.00
>> B(B > 15) = []       % delete based on a logical vector
B =
   14.00   15.00    8.00

2.7.6. Linear and Logarithmic Spaced Vectors

An alternative to the colon operator for creating vectors that span a range of numbers is the linspace function. The linspace function returns a row vector with a fixed number of elements. Use linspace when you want a certain number of evenly spaced elements in the vector.

The first and second arguments to linspace give the range. The optional third argument specifies the number of elements. The default for the third argument is 100, which is a nice value for creating a smooth line plot.

The logspace function also generates a sequence of numbers, but the numbers are evenly spaced on a logarithmic scale. The first two arguments to logspace specify the range as an exponent to 10 (\(1 \leadsto 10^1=10; 2 \leadsto 10^2=100\)). Like linspace, the third argument gives the number of elements desired. The default number of elements is 50.

>> x = linspace(0,10,5)
x =
        0    2.5000    5.0000    7.5000   10.0000
>> y = linspace(-pi, pi);
>> whos
Name      Size             Bytes  Class     Attributes

x         1x5                 40  double
y         1x100              800  double

>> logspace(0,2,5)
ans =
    1.0000    3.1623   10.0000   31.6228  100.0000