Skip to main content

Section 1.7 Examples and questions

These are additional examples for reviewing the topic we have covered. When reading each example, try to find your own solution before clicking “Answer”. There are also questions for reviewing the concepts of this section.

Write a script that calculates and displays the scalar product of two vectors: [1 2 ... n] and [n n-1 ... 1]. Use the first two digits of SUID as your value of n.

Answer
n = 28;
u = 1:n;
v = n:-1:1;
disp(u*v')

Explanation. Recall from Section 1.3 that a:h:b means a regularly spaced vector whose entries start with a, and then change by amount h until reaching b. When h is omitted, it is understood to be 1. So, this code makes u equal to [1 2 ... 28] and v equal to [28 27 ... 1]. Both are row vectors. Transposing the second vector into a column is necessary for their product to make sense, as noted in Section 1.4. Note that each of these lines ends with a semicolon, which prevents the intermediate results from being displayed on screen. Then disp displays the final result.

Write a script that creates and displays a row vector with 25 elements of the form [1 4 2 4 2 ... 2 4 1]. This particular sequence of numbers is used in “Simpson's Method” of numerical integration which we will encounter later.

Answer
v = ones(1, 25);
v(2:2:end) = 4;
v(3:2:end-2) = 2;
disp(v)

Explanation. The first line creates a vector of 25 ones, the second changes its even-numbered entries to 4, the third changes odd-numbered entries (except the first and last) to 2. Re-read Section 1.5 if this is unclear.

Create and display a “checkerboard” matrix of size 8×8: it should look like

1 0 1 0 ...
0 1 0 1 ...
1 0 1 0 ...
...........
Answer
A = zeros(8, 8);
A(1:2:end, 1:2:end) = 1;
A(2:2:end, 2:2:end) = 1;
disp(A)

Explanation. The first line creates an 8×8 matrix of zeros. The second works with the entries where both the row number and column number are odd, changing them to 1. The third does the same when both row and column numbers are even. The result is a checkerboard.

If in Example 1.7.1 we multiply the vectors in the different order, v'*u, there is no error message and Matlab produces a result. What does this result mean?

In Example 1.7.2, the pattern 14242....4241 requires an odd number of elements. We had 25 which is an odd number. If 25 is replaced by an even number, Matlab would not complain but the result would have a different pattern. What would it be? Try to answer without running Matlab.