Task: Create a column vector (C) and a row vector (R) each with three values. Determine the result of C*R and R*C.
A row vector (a variable with 1 row and several columns) is created with a concatenation command, R = [ 5 6 7 8].
A column vector (a variable with several rows and one column) is created with a concatenation command, C = [ 5; 6; 7; 8]. Recall that ; indicates the end of a row.
Another way to create a row vector is with x=zeros(1,5). A column vector is created with y=zeros(5,1). Once the variable is created, you will need to assign values to the different parts of the variable.
A matrix multiply involves an element-by-element multiplication of two lists along with a sum of the products.
Specifically, RC=R*C; will multiply each entry in the first row of R by the corresponding entry in the first column of C and add the resulting products to provide a value for the first row, first column of RC. For the arrays defined above, the result is one value (see the figure below).
Similarly, CR=C*R; multiplies the first value in C with the first value in R to get one number (no need for a sum) which is put in CR(1,1). The array CR contains every possible product of the entries in the two original arrays (see the figure below).
A slightly more complicated example: Let A= [1 2 3; 4 5 6] (2 rows and 3 columns) and B=[10 11; 12 13; 14 15] (3 rows and two columns).
A = ( 1 2 3 4 5 6) B = (10 11 12 13 14 15)
Then, C = A*B will multiply rows of A times columns of B and add the resulting products to form entries of C.
C(1,1) = 1*10 + 2*12 + 3*14 C(1,2) = 1*11 + 2*13 + 3*15and so forth.
In order for this operation to work, the number of elements in the rows of the first argument in the product must be the same as the number of columns in the second argument. If they don't match, MATLAB will stop with an error message "Error using *. Inner matrix dimensions must agree."
The shape of a vector or matrix variable is often important. As we will see later, MATLAB commands work on columns by default (that is, along the rows in a given column), so it is often important to create variables with the right shape.
A=[1:5] creates a row vector, a list with one row and 5 columns. You can create a column vector with A=[1;2;3;4;5] but this would be very painful (and subject to errors) for long vectors.
It is possible to change the shape of a matrix or vector variable with ', the matrix transpose operator. This operation flips a matrix around its diagonal (from upper left to lower right of the array). For example, A = [ 1 2; 3 4] is a 2x2 matrix,
A = ( 1 2 3 4)Then the transpose of A is
A' = ( 1 3 2 4)Note that the transpose operation converts a row vector into a column vector and vice versa.
B = ( 1 2 3 )
B' = ( 1 ) ( 2 ) ( 3 )
Script to complete this task:
% task25.m R=[5 6 7]; C=[5; 6; 7]; RC=R*C CR=C*R