Skip to the content of the web site.
## Laboratory 2

# 2.0 Further Commands of Matlab

# 2.1 Vectors and Vector Operations in Matlab

## 2.1.1 Row Vectors

## 2.1.2 Column Vectors

## 2.1.3 Efficient Constructors

### 2.1.3.1 The Colon (:) Operator

### 2.1.3.2 Vectors of Zeros, Ones, and Random Numbers

### 2.1.3.3 Linearly Separated Entries

## 2.1.4 Accessing Vector Entries

## 2.1.5 Suppressing Output

## 2.1.6 Vector Addition

## 2.1.7 Scalar Multiplication

## 2.1.8 Inner Products

# 2.2 Vector Functions

## 2.2.1 Vector Dimension/Length

## 2.2.2 Mathematical Functions

## 2.2.3 Functions of Vectors as Array Data Structures

### 2.2.3.1 Multiple Return Values

## 2.2.4 The Norm of a Vector

## 2.2.5 Element-wise Powers and Element-wise Products

## 2.2.6 Plotting

### 2.2.6.1 Additional Features

This laboratory will start with a review of the relevant background and will investigate two topics:

- Vectors and Vector Operations in Matlab (MATH 215), and
- Vector Functions and Plotting (MATH 211).

It is possible to re-execute previous commands by cycling through them using the ↑ key. The selection can be further refined by typing the first letter of the previous command you wish to run.

For example, suppose you run the following commands in Matlab:

>> sin( 3 ) ans = 0.1411 >> cos( 3 ) ans = -0.9900 >> ceil( pi ) ans = 4 >> cot( 3 ) ans = -7.0153 >> factorial( 3 ) ans = 6 >>

For example,

- At this point, pressing the ↑ key will cycle through the commands starting at the most recent,
- Typing
`c`and then pressing the ↑ key will cycle through the commands starting with that letter:`cot( 3 )`,`ceil( pi )`and`cos( 3 )`, in that order. - Typing
`co`and then pressing the ↑ key will cycle through the commands prefixed by`co`:`cot( 3 )`and`cos( 3 )`, in that order.

Alternatively, the *Command History* panel (select Desktop→Command History if it is not currently visible) allows you to double click on previous commands to re-execute them.

Finally, it is possible to highlight a command in the *Command History* panel, select a second command while holding the Shift key, and execute this block of commands by right-clicking on the selection and choosing *Evaluate Selection*.

In C/C++/Java/C#, defining an array (representing a vector) requires that the memory be allocated first and then, once the memory is allocated, assigning the entries. For example, the C code required to create a vector of size 10 storing values from 1 to 10 requires something like

double array[10]; for ( int i = 0; i < 10; ++i ) { array[i] = i + 1; }

Matlab, being designed for matrix calculations (*MATrix LABoratory*), allows the
user to enter vectors in a much more natural format.

In general, all vectors will be column vectors; however, it is necessary to start with row vectors. Spaces or commas separate columns and therefore

v = [5 4 9 8 1 2 7] v = [5, 4, 9, 8, 1, 2, 7]

both produce the same result. Matlab does try to anticipate operations. In this next example, the first two produce a 3-dimensional vector with -1 in the last location, but the third produces a 4-dimensional vector.

v = [1 2 3-4] v = [1 2 3 - 4] v = [1 2 3 -4]

In general, however, it is not advisable to perform calculates directly in the vector constructor.

Separating rows is done with a semicolon:

v = [5; 4; 9; 8; 1; 2; 7]

This is a little tedious, and therefore the best way to create a column vector is by taking the transpose of a row vector:

v = [5 4 9 8 1 2 7]'

Matlab provides other efficient vector constructors. The following include the colon operator and functional constructors.

The colon operator `a:b` is able to define a row vector where the values start
at `a` and increment up to `b`.

v = 1:10 v = -7:7 v = pi:10 v = 1:pi

From the behaviour shown above, it should be clear that `a:b` constructs a row vector
of length of the
form .

Most often, however, the end points of such a vector will be integers.

Rather than stepping by 1, it is possible to construct a vector which steps by
an amount `k`:

v1 = 1:3:10 v2 = pi:0.5:10 v3 = 1:0.1:pi v4 = pi:-0.1:1 v5 = 10:-1:0

From the behaviour shown above, it should be clear that `a:k:b` constructs a row vector
of length of the
form and
that `k` may be positive or negative, but not zero.

An -dimensional row vector of zeros, ones, pseudo-random numbers selected uniformly from the interval ,
and pseudo-random numbers following a normal distribution with mean (average value) zero () and standard deviation one () (this is called a *standard normal*) may
be constructed by the following four functions:

as follows:

zeros( 1, n ) ones( 1, n ) rand( 1, n ) randn( 1, n )

while column vectors may be created using

zeros( n, 1 ) ones( n, 1 ) rand( n, 1 ) randn( n, 1 )

For example,

zeros( 3, 1 ) ans = 0 0 0 ones( 1, 8 ) ans = 1 1 1 1 1 1 1 1 rand( 5, 1 ) ans = 0.2830 0.6683 0.8166 0.4157 0.4708 randn( 1, 9 ) ans = -1.2029 0.3323 0.5496 0.7657 -0.4186 -1.3979 -0.9079 0.3498 -0.0441

Finally, there is the `linspace` function:

v1 = linspace( 1, 2, 10 ) v2 = linspace( 1, 2, 100 );

The call `linspace( a, b, n )` creates a row vector containing
equally spaced entries: if this produces
the row vector .

The entries of a vector may be accessed using parentheses.

Unlike C/C++/Java/C#, the entries of an n-dimensional vector
are numbered 1 through n and not 0 through n - 1. |

u = [0.1 2.3 4.5 6.7 8.9] u(1) u(2) u(3) v = [0.1 2.3 4.5 6.7 8.9]' v(1) v(2) v(3)

Matlab also allows you to access the last entry of a vector independent of the dimension:

v = [0.1 2.3 4.5 6.7 8.9]' v(end) v(end-1) v(end-2)

You may have already noticed that it becomes frustrating to see unnecessary output. The output of a command in Matlab may be suppressed by following the command with a semicolon:

v = [0.1 2.3 4.5 6.7 8.9 10.1 12.3 14.5 16.7 18.9]'; v(1) v(2) v(6)

To add or subtract two vectors, they must both be column vectors or they must both be
row vectors. It is not possible to add a row vector and a column vector. The
notation is quite simple, `u + v`, and this calculates

.

Matlab will return an error if the dimensions and shape (row or column) do not match.

The operation `u - v` works as expected.

If you replace one of the vectors with a scalar, Matlab will add or subtract that scalar onto each entry of the matrix:

u = [5 9 5 2 8]'; v = (1:5)'; u + v ans = 6 11 8 6 13 u - v ans = 4 7 2 -2 3 u + 5 ans = 10 14 10 7 13 u - 1 ans = 4 8 4 1 7

If `a` is a scalar and `v` is a vector, then the product `a*v`
calculates the scalar product

.

The operation `u/a` also works as expected.

Calculating the inner product of two vectors requires more knowledge of linear algebra to understand; however, we will currently simply state:

**The inner product is a product of a row vector and a column vector.**

The operator is the product `*` and as almost all vectors will be column vectors, we
usually write the inner product as `u'*v`:

% Three column vectors u = [1 2 3]'; v = [1 0 -2]'; w = [4 0 2]'; u' * v u' * w v' * w

As this demonstrates, the vectors `v` and `w` are orthogonal. If we were to plot these two
vectors, they would be perpendicular to each other.

We will look at a number of vector functions.

The dimension of a vector may be found by calling `length`. For example,

u = [0.1 2.3 4.5 6.7 8.9]; length(u) v = [0.1 2.3 4.5 6.7 8.9 10.1 12.3 14.5 16.7 18.9]'; length(v)

If a vector is passed as an argument to a mathematical function such as `sin`, the result
is a vector evaluating the function at all of the entries. For example:

u = [0.1 2.3 4.5 6.7 8.9]'; sin(u) [sin(0.1) sin(2.3) sin(4.5) sin(6.7) sin(8.9)]' v = [-0.917 -0.428 -0.085 0.635 -0.543 0.729 0.791 0.642 0.548 -0.733]'; abs( v );

The result is similar for all the functions shown in Laboratory 1.

We will now consider five functions which treat vectors not as mathematical objects, but
rather as list data structures as you are currently seeing in ECE 250 *Algorithms and Data Structures*.

`sum`- return the sum of the entries of the vector,`sort`- sort the entries of the vector,`min`- find the minimum entry in the vector,`max`- find the maximum entry of the vector,`mean`- find the average value of the entries of the vector,`std`- find the standard deviation of the entries of the vector, and`median`- find the median entry of the vector.

The last three which provide statistical descriptions of the data are not required for this course; however, it is useful to be aware that they exist.

These will be demonstrated here:

u = [1 2 3 4 5 6 7 8 9 10]'; v = [-0.917 -0.428 -0.085 0.635 -0.543 0.729 0.791 0.642 0.548 -0.733]'; sum( u ), sum( v ) sort( u ), sort( v ) min( u ), min( v ) max( u ), max( v ) mean( u ), mean( v ) std( u ), std( v ) median( u ), median( v )

Notice that we may use other functions to find some of these:

mean( u ), sum( u ) / length( u ) mean( v ), sum( v ) / length( v )

Unlike C/C++/Java/C#, Matlab allows multiple return values if this is supported
by the function. For example, `max` by default returns simply the maximum entry
of the vector. If you provide two return values, the second variable is assigned
the position of the maximum value:

v = rand( 1, 8 ) v = 0.5433 0.4213 0.6481 0.1207 0.5822 0.5572 0.7129 0.6326 max( v ) ans = 0.7129 m = max( v ) m = 0.7129 [m p] = max( v ) m = 0.7129 p = 7

The Euclidean norm or 2-norm of a vector may be found by calling the `norm` function:

v = [3 4]'; norm(v)

The 2-norm is written and calculated as

.

The Euclidean norm is the the square root of the inner product of a vector with itself:

u = [5 3 2 5 9]' norm( u ) ans = 12.0000 sqrt( u' * u ); ans = 12

and

v = rand( 4, 1 ) v = 0.4833 0.0403 0.3107 0.4471 format long norm( v ) ans = 0.729144511970571 sqrt( v' * v ) ans = 0.729144511970571 sqrt( sum( v.^2 ) ) ans = 0.729144511970571

The purpose a norm is to determine how "far apart" to vectors are. Normally, we think of distance as Euclidean distance; however, suppose you wanted to get from the front entrance of the Royal Ontario Museum and go to Charles St. (see Figure 1), the Euclidean distance would significantly underestimate the distance you would be forced to walk. Instead, you would want a different distance: if was the coordinates of the entrance of the ROM and was the coordinates of the location on Charles St., it follows that the vector connecting the two points is and if the streets were north-south and east-west, the distance you would have to walk is .

Figure 1. The area around the Royal Ontario Museum (courtesy of Google Earth).

This distance has a name, too, and it is called the 1-norm:

.

This is shown in Figure 2 which displays a vector in blue together
with the calculation of the 1-norm. The one norm is the *length* of
the two vectors.

Figure 2. Given a vector (in blue), the 1-norm is the sum of the absolute
values of the entries of the vector.

This can be calculated using two functions we have already seen:

v = [3.2 -0.1 4.7 -5.9]'; sum( abs( v ) ) ans = 13.9000

However, the `norm` may be passed an additional argument, `1`:

norm( v, 1 ) ans = 13.9000

Figure 3 shows the application of the 1-norm. Consider any path which moves from the base of a vector to its point moving only in directions parallel to the axes. One such path is shown in purple in Figure 3. The length of any such path is always equal to the 1-norm.

Figure 3. Two paths of equal length starting from the base of a vector
(in blue) moving towards the tip.

The ∞-norm returns the maximum of the absolute values of the entries:

.

As with the 1-norm, it is possible to calculate this with either two Matlab functions or the `norm` function
with a second argument:

v = [3.2 -0.1 4.7 -5.9]'; max( abs( v ) ) ans = 5.9000 norm( v, Inf ) ans = 5.9000

Suppose we wish to raise each entry in a vector to a specific power. Because multiplication for vectors is not defined mathematically (what is the product of two vectors?), this is a data-structure operation and not a mathematical operation.

Because Matlab reserves `^` for usual exponentiation, e.g., `v^3 = v*v*v`, the means of indicating an
element-wise operation is to prefix the operator with a `.`; for example

v = [1 2 3]'; v.^2 v.^3

At this point, it should be apparent that if we want, given two vectors and , and we want to calculate the vector , it follows we must use

u = [5 1 4]'; v = [1 2 3]'; u.*v

**This will not be used in your Linear Algebra course; however, it is very important as a data-structure operation.**

The plotting function

plot( [x1 x2 x3 x4 ... xn], [y1 y2 y3 y4 ... yn] )

plots the points and connects each pair of points with a line.

For example, this could be used to plot a function such as the sine function:

x1 = linspace( 0, 2*pi, 10 ); plot( x1, sin(x1) )

Notice that the plot (in blue) is quite clearly piecewise linear: there are only ten points and connecting these with straight lines leads to an unpleasing visual effect. If we increase the number of points, we get a better plot.

x2 = linspace( 0, 2*pi, 100 ); plot( x2, sin(x2) )

Two issues: you will note that in creating a second plot, the first plot was replaced. What
happens if we want to view the second plot together with the first plot? Matlab allows you to
indicate that the plot should not be replaced by using the `hold on` command. In addition,
to change the colour of the plot to red, pass a third argument `'r'`:

x1 = linspace( 0, 2*pi, 10 ); plot( x1, sin(x1) ) hold on x2 = linspace( 0, 2*pi, 100 ); plot( x2, sin(x2), 'r' )

The possible colours, by default blue) are shown in Table 1.

Table 1. Matlab plotting colours.

Symbol | Colour | Comment |
---|---|---|

r | red | |

g | green | |

b | blue | |

c | cyan | light blue |

m | magenta | bright purple |

y | yellow | |

k | black | |

w | white |

Other features which changed in a plot include the type of line (by default solid) shown in Table 2 and the symbol used to mark each point (by default, a single point) shown in Table 3.

Table 2. Matlab plotting lines.

Symbol | Colour | Comment |
---|---|---|

- | solid | |

: | dotted | |

-. | dashdot | |

-- | dashed | |

| no line | When only a point (Table 3) is specified. |

Table 3. Matlab plotting points.

Symbol | Colour | Comment |
---|---|---|

. | point | |

o | circle | |

x | '×' | |

+ | '+' | |

* | star | |

v | triangle | pointing down |

^ | triangle | pointing up |

< | triangle | pointing left |

> | triangle | pointing right |

s | square | |

d | diamond | |

p | pentagram | |

h | hexagram |

These can be found using the command

>> help plot

All other modifications to plots are done through further Matlab commands:

The `grid` function turns on a grid. By simply calling `grid`, it uses a
default grid. This can also be used as a function which is passed
parameters which describes the grid. See `help grid`.

The `title` function allows the user to give the plot a title:

title( 'This is a Plot' )

Again, see `help title` for further options.

Labels may be given to both axes using the
`xlabel` and
`ylabel`
functions.

xlabel( 't' ) ylabel( 'f(t)' )

The range of the x- and y-axes may be set using the
`xlim` and
`ylim` functions, respectively.

xlim( [0 1] ) % set the visible range on the abscissa or x-axis to [0, 1] ylim( [-1 1] ) % set the visible range on the ordinate or y-axis to [-1, 1]