You are on page 1of 10

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.

Enter the following code in MATLAB:

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

A:

B:

C:

In general, how do you display a matrix in MATLAB?



Enter the following matrix into MATLAB in three ways. Write your codes on the space provided.
Refer to the descriptions below.

[








]

Method 1: Type in the matrix element-per-element.
Method 2: Type in the matrix as a row of four column vectors.
Method 3: Type in the matrix as a column of four row vectors.

1:



2:



3:



What matrix is formed by entering A? What does the command do?







2

Using the same matrix A from the previous section, type in the following codes.

B = A(3,4);
C = A(1,2);
D = A(5,6);

Display the variable outputs in MATLAB. In general, what does the command X = A(i,j) do?



Now enter the following codes:

A(2,4) = 3;
A(3,2) = 1;
A(1,5) = 5;

In this case, what does the command A(i,j) = X do?



Enter the following codes:

M = [2:10];
N = [2:2:10];
O = A(:, 1);
P = A(3, :);

Display the outputs in MATLAB. Can you make a generalization regarding the use of colon
notations in MATLAB? Try to use the built-in help function of MATLAB to answer this question.




Colons can also be used to refer to subsets of matrices. For the following matrix:

[








]

Declare another variable X that refers to the matrix formed by elements from the 2
nd
3
rd
rows,
and 2
nd
3
rd
columns. Enter your code in the space provided.




The following are some of the matrix-creating functions in MATLAB. The syntax for each
function is provided. Try to determine what is displayed for each command.

v=[a b c d]; %a b c d insert your own value
A=diag(v);
P=diag(A);

B=eye(n); %n may refer to any integer
C=eye(m,n); %m,n may refer to any integer

D=ones(m,n);
E=zeros(m,n);


3

The following are some of the vector-creating functions in MATLAB. The syntax for each
function is provided as well.

F=linspace(startValue,endValue,nelements)
%startValue and endValue may refer to any number. nelements may refer to any
integer.

F=logspace(startValue,endValue,nelements)
%startValue and endValue may refer to any number. nelements may refer to any
integer.

Enter the following on your command window:

>> A = [5 7 -2 4 3];
>> A*2
>> A+3
>> A-1
>> A(1)+A(3)
>> [sum(A) prod(A)]
>> diff(A)
>> cumsum(A)
>> [max(A)min(A)]
>> [v,ind] = max(A)
>> A'

>> A = [1 5 3;4 2 6];
>> A*2
>> A+3
>> A-1
>> A(1,3)+A(2,1)
>> sum(A)
>> sum(sum(A))
>> prod(A)
>> max(A)
>> min(A)
>> cumsum(A)
>> A'

What can you conclude regarding the syntax and use of sum, prod, diff, cumsum, min, and
max on vectors and matrices?




>> B = [1;2;3]
>> length(B)
>> T = B'
>> length(T)

>> C = 1:10
>> C = C*2 + 3
>> C(3:7)
>> D = 1:2:10
>> E = 1:3:10
>> length(D)
>>[D(end-2) D(end)]

>> B = linspace(5,20)
>> C = linspace(5,20,4)
>> A = [B C]

4

>> N = 7;
>> T = logspace(1,N,N)
>> length(T)
>> V = logspace(0,N-1,N)

What can you conclude regarding the syntax and use of length?




>> r = rand(2)
>> r = r*10
>> floor(r)
>> ceil(r)

>> V1 = 1:3;
>> V2 = 4:6;
>> V1'*V2
>> V1*V2'
>> V1.*V2

>> F = [5 12 -1 2 9];
>> [mean(F) median(F)]
>> mode(F)
>> fliplr(F)
>> fliplr(F(4:end))

What can you conclude regarding the syntax and use of mean, median, mode, and fliplr?











5

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
3 1 9 3 4 1
9
1 4
2
A x v
(
(
(
(
(
= = =
(
(
(
(




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 per 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
9 7 6 12
4 14 15 1
M
(
(
(
=
(
(



Trivia: The matrix above is also a 4x4 magic square. You can recreate matrix M without copying
each element. (Discover how!)





6

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

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 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, 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 is this so?





7

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, arranged from
highest to lowest precedence:

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

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 3
rd

column of matrix A. Entering A(3,4) will return an error message from MATLAB, since matrix
A does not have a 4
th
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)

8

MATLAB will extract the element from the 2
nd
row and 3
rd
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 1
st
column, or A(3,1), is 13.

>> A(3,1) = 16

Entering the command above will assign a new value of 16 to the 3
rd
row and 1
st
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?

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 commands below:

>> vector1 = 1:10

When an increment is not indicated in the command, MATLAB, by default, will use an
increment of one. The command above will display a row vector with elements from 1 to 10,
with increments of 1. 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:
9

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

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

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

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

Function Operation Performed
v = [elements];
A = diag(v);
Create a matrix A with a diagonal whose elements are that of vector
v
A = [elements];
v = diag(A);
Create a column vector v whose elements are that of the diagonal
of 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 1s with size nrows x ncolumns
zeros(nrows,ncolumns) Create a matrix of 0s 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
2


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
10


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.

ADDITIONAL NOTES

Given the following polynomial form:

( )
1
1 2 1
n n
n n n
P x c x c x c x c

+
= + + + +

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

>> p = [c
1
c
2
... c
n
c
n+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


CHALLENGE

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

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

You might also like