0% found this document useful (0 votes)
4 views

Week 6 C3 Vectors in MATLAB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Week 6 C3 Vectors in MATLAB

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1

NAME: DATE:

SECTION: SCORE:

WORKSHEET
Matrices and Vectors in MATLAB®
Instructions: This shall serve as your proof of attendance for this meeting. Write what is asked of you on
the space provided beside each item.

A. CREATING VECTORS AND MATRICES

Enter the following statements in the command window, and write down the outputs.

>> A = [3 2 3; 5 7 1; 9 0 4]
>> B = [6 7 9 0 5]
>> C = [9; 3; 6; 1]

A:

B:

C:

How are matrices created in MATLAB®? What separates the rows? What separates the columns?

Whitespaces and commas have the same effect in creating matrices (i.e. [6,7,9,0,5] is also valid).
Now, store the following new matrix into variable A.

16 2 3 13
𝐴=[ 5 11 10 8]
9 7 6 12
4 14 15 1

After doing so, type the following statements and look at the outputs:

>> A'
>> A''

What is the relationship between matrix A and matrix A'?

Using the same matrix A from the previous section, type the following statements:

>> A(1,1) What is returned by A(i,j)? What happens when i and/or j are invalid?
>> A(1,2)
>> A(4,3)
>> A(3,5)
2

B. COLON NOTATION

Retain matrix A in your workspace. Enter the following statements and study the outputs carefully:

>> p = [1:5] What does the code J:K mean?


>> q = [2:2:10]
>> r = [10:-1:5]
What does the code J:D:K mean?
>> A
>> A(:, 1)
>> A(3, :)
>> help colon

Colons can also be used to call submatrices of a larger matrix. Type the following and write the outputs:

>> P = A(:, 3:4) P:


>> Q = A(2:4, :)
>> R = A(1:3, 2:4)

Q:

R:

C. EDITING MATRICES AND VECTORS

Retain matrix A in your workspace. Enter the following statements:

>> A(2,4) = 3; What does the command A(i,j) = X do?


>> A(3,2) = 1;
>> A(1,:) = 0;
>> A

Retaining the current state of matrix A, type the following commands and observe every output.

>> B = [2 0 1 5] How can rows and columns be inserted from a matrix? What
>> C = [8 7 0 0 0]' happens when there is size mismatch during insertion?
>> A = [A; B]
>> A = [A C]
>> A = [A; B]
>> A = [A(:,1) C A(:,2:5)] How can rows and columns be deleted from a matrix?
>> A(2,:) = []
>> A(:,1) = []
>> A(1,2) = []

D. BUILT-IN MATRICES AND VECTORS

Type the following codes and study the outputs. Use the help command to understand them better.

>> B = [2 0 1 5]; >> rand(3) >> magic(4)


>> B = diag(B) >> rand(3) >> spiral(5)
>> B = diag(B) >> randi(10,5) >> pascal(7)
>> ones(4,3) >> randi(10,5) >> vander([1 2 3 4 5])
>> zeros(3,2) >> toeplitz([1 2 3 4])
>> eye(5)
3

To generate uniformly spaced values in one row vector, type the following, and observe the outputs:

>> F = linspace(0,1,11) In the syntax, linspace(x1, x2, n), what are x1, x2, and n?
>> F = linspace(0,1,6)
>> F = linspace(1,100)'
>> [F F*2 F*5]
>> G = logspace(0,2,5)
>> log10(G)

E. VECTOR AND MATRIX OPERATIONS

MATLAB® can compute sums, differences, products, and inverses of matrices very efficiently. It was
made for that purpose. Type the following on your command window. You can verify results by hand.

>> X = [5 7 -2 4 3]; >> P = magic(2); >> R = [1 1;0 1];


>> X*2 >> Q = spiral(2); >> S = randi(10,2);
>> X+3 >> P*Q >> R + 2*S
>> X(1) + X(3) >> Q*P >> 4*R – S
>> X(1:4) + X(2:5) >> P*eye(2) >> R^3
>> eye(2)*P

There are 2 ways to implement division: Left division using ‘\’ and right division using ‘/’. In matrix algebra,
‘matrix inverse’ is the more accepted term than ‘matrix division’. Type the following and observe:

>> A = [2 1;-1 3]; List down 1 or 2 notes on how to use left and right division.
>> B = [4 5;0 1];
>> C = A*B; D = B*A;
>> C/B
>> D/A
>> A\C
>> B\D

For multiplication, exponentiation, and division, there are 2 versions of their operators. One version uses
‘*’, ‘^’, and ‘/’. The other version uses ‘.*’, ‘.^’, and ‘./’. Type the following to see the difference:

>> U = [4 3;2 1]; NOTE: Check the results by hand, before you answer!
>> V = [-2 0;3 2]; What is the difference between the 2 versions of the operators?
>> U*V
>> U.*V
>> U^2
>> U.^2
>> U.^V
>> U./V

F. MATLAB® FUNCTIONS FOR VECTORS AND MATRICES

All built-in mathematical functions from the previous worksheet can also take matrices and vectors as
inputs. They are evaluated element-by-element. In addition, the following functions are also useful:

>> Z = 1:10; >> Y = [1 5 3;4 2 6]; >> max(Y)


>> length(Z) >> size(Y) >> max(Y')
>> sum(Z) >> size(Y') >> min(Y)
>> sum(Z(1:8)) >> length(Y) >> min(Y')
>> sum(Z(8:end)) >> sum(Y) >> max(Z)
>> diff(Z) >> sum(Y') >> min(Z)
>> prod(Z) >> sum(sum(Y)) >> X = Y(:)
>> cumsum(Z) >> Y(end) >> reshape(X,2,3)
4

MODULE 3
Matrices and Vectors in MATLAB®
OBJECTIVE

At the end of this module, you should be able to:


1. Apply knowledge on vectors and matrices on different MATLAB operations.
2. Use array operators with vectors and matrices.
3. Know how to use the functions rand, zeros, ones, and eye.
4. Know how to use additional built-in functions such as sum, diff, prod, max, min,
length, size, diag, etc.

MATRICES AND VECTORS

Consider the following matrix A, column vector x, and row vector v:

5 
3 2 7 
A = 3 1  x=  v = 9 −3 4 1
9
1 4  
2

The following matrices can be displayed in the MATLAB® command window by typing in the following
commands:

>> A = [3 2; 3 1; 1 4]
>> x = [5; 7; 9; 2]
>> v = [9 -3 4 1]

Matrices and vectors are denoted by elements inside a set of brackets “[ ]”. Column vectors use
semicolons to separate the elements of each row (as seen in vector x above). Row vectors use spaces to
separate between elements in a row (as seen in vector v). Try to recreate the following matrix on your
MATLAB® command window:
16 2 3 13
 5 11 10 8 
M= 
 9 7 6 12
 
 4 14 15 1 

MATRIX OPERATIONS

MATLAB® can also carry out several matrix operations. Matrix transposition can be carried out by
appending an apostrophe sign at the end of the matrix variable:

>> A = [1 2 3; 5 7 11; 13 17 19];


>> A'
ans =
1 5 7
2 7 17
3 11 19
5

Addition and subtraction of matrices are done element-by-element. When multiplying element from one
matrix by an element in another matrix, we add a dot (.) operator just before the actual operator sign. An
example of this is what we call element-by-element multiplication:

>> u = [10 9 8];


>> v = [1 2 3];
>> u.*v

When you multiply elements from u by elements from v, adding a dot operator before the multiplication
sign signifies element-by-element multiplication (and not matrix multiplication). In this case, the product
matrix will yield:

ans =
10 18 24

Removing the dot operator will signify matrix multiplication. Matrix multiplication follows a certain rule
(discussed in Chapter 1: Linear Algebra), as shown in the following example:

>> u*v'
ans =
52

Here is another one:

>> u'*v
ans =
10 20 30
9 18 27
8 16 24

Entering u*v in your command window will result to MATLAB® giving you an error message. Why?

MATLAB® follows a certain order of operations, which is consistent with the known order in
mathematics. Shown below is the operator precedence observed in MATLAB®, from highest to lowest:

Operator Meaning
( ) Parenthesis
^ .^ ' Exponentiation, Transposition
~ Not
* / .* ./ Multiplication, Division
+ - Addition, Subtraction
: Colon Operator
> >= < <= == ~= Relational Operators
& And (true if both are true)
| Or (true if one condition is true
6

Can you replicate the following 10x10 multiplication table, in the shortest MATLAB® code possible?

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 

3 6 9 12 15 18 21 24 27 30 
 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
 
8 16 24 32 40 48 56 64 72 80 
 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100

SUBSCRIPT NOTATION

Elements in a matrix are assigned a certain index (or position indicator). The syntax A(i,j) refers to an
element of matrix A that is found in the i-th row and j-th column. For example:

>> A = [1 2 3; 5 7 11; 13 17 19];


>> A(3,3)

The command above will display 19, which is the element found in the 3 rd row and the 3rd column of
matrix A. Entering A(3,4) will return an error message from MATLAB®, since matrix A does not have a
4th column.

The syntax A(i,j) can be used to either extract elements from a matrix, or assign values to another
matrix. For example:

>> extractedelement = A(2,3)

MATLAB® will extract the element from the 2 nd row and 3rd column of A (which is 11) and store it in the
variable extractedelement. Consider another example below. At present, the element in the 3 rd row
and 1st column, or A(3,1), is 13.

>> A(3,1) = 16

Entering the command above will assign a new value of 16 to the 3rd row and 1st column of matrix A. Now
try the following command:

>> A(4,1) = 20

What happens now? Can you provide a generalization for this type of assignation?
7

VECTOR GENERATION

Vectors can also be generated easily when a given trend is observed among its elements. The colon
notation makes the creation of these kinds of vectors possible. The syntax is given as:

startValue:endValue
startValue:increment:endValue

Try the following command below:

>> vector1 = 1:10

When an increment is not indicated in the command, MATLAB®, by default, will use an increment of 1.
The command above will display a row vector with elements from 1 to 10, increasing by increments of 1:

vector1 =
1 2 3 4 5 6 7 8 9 10

If an increment of 2 is implemented:

>> vector1 = 1:2:10

MATLAB® displays the following:

vector1 =
1 3 5 7 9

The colon notation can also be used to extract elements from a matrix. For example:

>> matrixB = [1 2 3; 4 5 6; 7 8 9];


>> firstrow = B(1,:);
>> firstcolumn = B(:,1);
>> subsetB = B(2:3,1:2);

The variable firstrow will now contain the elements from the first row, while firstcolumn will
contain elements from the first column. Can you now generalize how colon notations can be used to
extract elements from a matrix? What do you think will subsetB contain?

There are additional functions that can also generate row vectors. The functions linspace and
logspace generate vectors based on how many elements the user wants inside these vectors.
linspace generates vector elements with uniform linear spacing, while logspace generates elements
with uniform logarithmic spacing. The syntax for the two functions is given us:

linspace(startValue,endValue)
linspace(startValue,endValue,nelements)

logspace(startValue,endValue)
logspace(startValue,endValue,nelements)

logspace generates vectors from a value equal to 10startValue to 10endValue. When not indicated in the
command, logspace assumes a default value of 100 elements.
8

Some special types of matrices can also be generated with several MATLAB® functions. The following
table summarizes them:

Function Operation Performed


v = [elements]; Create a matrix A with a diagonal whose elements are that of vector v
A = diag(v);
A = [elements]; Create a column vector v whose elements are that of the diagonal of
v = diag(A); matrix A
eye(n) Create an identity matrix with size n (square)
eye(nrows,ncolumns) Create an identity matrix with size nrows x ncolumns
ones(nrows,ncolumns) Create a matrix of 1’s with size nrows x ncolumns
zeros(nrows,ncolumns) Create a matrix of 0’s with size nrows x ncolumns

Note: The diag function first identifies the value inside of the parenthesis. If it detects a matrix, it returns
the values of the principal diagonal as a column vector. If it detects a vector, it uses the values of the given
vector for the principal diagonal of the matrix it will create.

Can you create a table of trigonometric functions on MATLAB®, with the following format?

θ sin(θ) cos(θ)
0
π/4
π/2
3π/4
π
5π/4
3π/2
7π/4

LOADING MATRICES FROM EXTERNAL FILES

MATLAB® can load external files into its environment, and automatically detect matrices and stores
them as variables. If you have a text editor installed in your computer, type the following:

1 2
2 3
3 4
4 5

Save the file as matrixC.txt. Now go to your MATLAB® command window, and enter the following
command:

load matrixC.txt

MATLAB® loads the file and saves it in your Workspace as a variable. Notice that the elements of the text
file are detected by MATLAB® as elements of a matrix.
9

ADDITIONAL NOTES

A. Polynomials as Vectors
Given the following polynomial form:

Pn ( x ) = c1 x n + c2 x n−1 + + c n x + c n +1

The coefficients can be stored in a vector in decreasing powers of x:

>> p = [c1 c2 ... cn cn+1];

Several functions can be used on this vector p:

Function Operation performed


poly Create a polynomial having specified roots
polyder Differentiate a polynomial
polyval Evaluate a polynomial
polyfit Polynomial curve fit
roots Find roots of a polynomial

B. Matrices of Higher Dimensions


A matrix with N > 2 dimensions can be created using a command called ‘cat’, which stands for
concatenation. Higher dimensional matrices can be entered by appending 2 or more previously declared
2-dimensional matrices. For example, to create a 3-by-3-by-2 matrix, see the following input-output.

>> a = magic(3); b = pascal(3);


>> c = cat(3,a,b)

c(:,:,1) =

8 1 6
3 5 7
4 9 2

c(:,:,2) =

1 1 1
1 2 3
1 3 6

CHALLENGE

What is the result of the code shown below? What does the code do?

>> t = [1 2 3; 4 5 6];
>> t([1 2 3])
>> t(t)
>> t(t(t))

You might also like