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

Experiment 2 - MATLAB Fundamentals II

Uploaded by

marahhwaitat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Experiment 2 - MATLAB Fundamentals II

Uploaded by

marahhwaitat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Copyright © (2020) Dr.

Ashraf Suyyagh – All Rights Reserved

University of Jordan

School of Engineering and Technology

Department of Computer Engineering

Practical Numerical Analysis (CPE313)

Experiment 2 - MATLAB Fundamentals II


Author: Dr. Ashraf E. Suyyagh

Table of Contents
Experiment 2 - MATLAB Fundamentals II ............................................................................................. 1
Scalars, Vectors, and Matrices .............................................................................................................. 1
Vectors ............................................................................................................................................... 2
Creating Vectors ............................................................................................................................ 2
Appending Vectors ........................................................................................................................ 4
Useful techniques for creating large vectors ................................................................................. 5
Matrices.............................................................................................................................................. 7
Vector and Matrix Indexing and Addressing ................................................................................. 9
Special MATLAB Vectors and Matrices ...................................................................................... 12
Matrix Manipulation...................................................................................................................... 14
Sorting Vectors and Matrices ...................................................................................................... 18
Vector and Matrix Mathematical Operations ............................................................................... 19
Vector and Matrix Logical Operations ......................................................................................... 24
Multidimensional Matrices ........................................................................................................... 26
Data Import and Pre-processing .......................................................................................................... 28
Loading and Storing MATLAB Variables ......................................................................................... 28
Using the Interactive Import Tool ..................................................................................................... 28
Importing Spreadsheets using the GUI tool ................................................................................ 29
Importing Text Files using the GUI Tool ...................................................................................... 29

Scalars, Vectors, and Matrices


In the previous experiment, we have introduced single-valued variables and many of the scalar
operations associated with them. However, MATLAB really shines when working with vectors and
matrices. In many other programming languages that you might have learnt already (C++ and Java),
you stored vectors and matrices inside 1D and 2D arrays, respectively. You conducted all array
related operations through loops. This is time consuming and error prone.

In MATLAB, storing vectors and matrices is straightforward through a simple assignment operator.
Further, all associated operations DO NOT need loops. You can use simple mathematical
operations almost directly.

This is one main reason why MATLAB is widely used by millions of engineers and scientists.
For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 1 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

MATLAB vectors and arrays can hold numbers, characters (array of strings), or logical values (0 or
1). But an array or matrix CANNOT hold a mix of these types at the same time.

Previously, when we used the whos command, we noticed that all single-valued variables (scalars)
had a size of 1x1. MATLAB treats scalars as one-element vectors of size 1x1.

Vectors
A vector is simply a one-dimensional matrix. In Physics and Mathematics, and other engineering
courses, you often worked with vectors that are projected onto a 3D Cartesian coordinate system.
The vector in this coordinate system is often given as:

where are the scalar magnitudes of the vector projections onto the Cartesian axes.

Creating Vectors

In MATLAB, you can easily define a 3D vector in two forms: a row vector or a column vector.

So, we can write in row form: or column form: as follows:

Row form (Use commas to separate elements):

v1 = [5, 8, -9]

v1 = 1×3
5 8 -9

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 2 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

Column form (Use semicolons to separate elements):

v2 = [5; 8; -9]

v2 = 3×1
5
8
-9

You can convert between column and row vectors using the transpose operator ('), for example:

v3 = [5, 8, -9]' % Creates a column vector by transposing a row vector

v3 = 3×1
5
8
-9

v4 = [5; 8; -9]' % Creates a row vector by transposing a column vector

v4 = 1×3
5 8 -9

v5 = v3' % Creates a column vector by transposing a row vector

v5 = 1×3
5 8 -9

Vectors are not restricted to 3-elements. You can create row or column vectors of any size . Use
whos command with the variable name to see detailed info about the vector variable.

v6 = [0.5, 6, 9, 0, 0, 12, -8, 8] % This is a 1x8 row vector

v6 = 1×8
0.5000 6.0000 9.0000 0 0 12.0000 -8.0000 ⋯

whos v6

Name Size Bytes Class Attributes


v6 1x8 64 double

v7 = [0.9; 0; 0; 9; -9; 1; -3; 6] % This is a 8x1 column vector

v7 = 8×1
0.9000
0
0
9.0000
-9.0000
1.0000
-3.0000
6.0000

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 3 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

whos v7

Name Size Bytes Class Attributes

v7 8x1 64 double

Note that unlike C++ or Java, we did not need to declare and reserve memory for a 1D array then
use loops to store elements in the 1D array. It is straightforward and simple.

Appending Vectors

You can create vectors from other vectors by appending them together. The only condition is that
these vectors are of the same data type and shape; that is, you can only append row vectors
together, or column vectors together, but not both.

Let's append the row vector with the row vector (as before, use the comma in creating row
vectors):

v8 = [v1, v6]

v8 = 1×11
5.0000 8.0000 -9.0000 0.5000 6.0000 9.0000 0 ⋯

Let's append the column vector with the column vector (as before, use the semicolon in
creating column vectors):

v9 = [v2; v7]

v9 = 11×1
5.0000
8.0000
-9.0000
0.9000
0
0
9.0000
-9.0000
1.0000
-3.0000

Appending row and column vectors will result in an error, try:

[v1, v7]
[v1; v7]

You can append row vectors with column vectors ONLY if you transpose one of them to match the
other, try:

v10 = [v1, v7'] % Appending into row vector

v10 = 1×11
5.0000 8.0000 -9.0000 0.9000 0 0 9.0000 ⋯

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 4 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

v11 = [v2; v6'] % Appending into column vector

v11 = 11×1
5.0000
8.0000
-9.0000
0.5000
6.0000
9.0000
0
0
12.0000
-8.0000

Useful techniques for creating large vectors

Many times, you will work with vectors of hundreds or thousands of elements. Hand entry is
impossible.

If you want to create a vector with regularly spaced elements, use the colon (:). The syntax is
where:

• is the starting point.


• is the spacing between elements.
• is the upper limit (not necessarily the last element, but the last element will not exceed ).
if is an integer multiple of , then will be the last element.

In this syntax, the number of elements is given by:

v12 = [0: 2: 8]

v12 = 1×5
0 2 4 6 8

v13 = [0: 2: 7]

v13 = 1×4
0 2 4 6

v14 = [1: 1: 10]

v14 = 1×10
1 2 3 4 5 6 7 8 9 10

Notice that if don't specify a value for the increment , the default value is .

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 5 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

v15 = [1:10]

v15 = 1×10
1 2 3 4 5 6 7 8 9 10

The increment can be a floating-point number, or negative:

v16 = [0: 0.25: 4]

v16 = 1×17
0 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 ⋯

v17 = [10: -2: -10]

v17 = 1×11
10 8 6 4 2 0 -2 -4 -6 -8 -10

To retrieve the number of elements in a vector, use the length command:

length(v12)

ans = 5

length(v16)

ans = 17

If you need to create a vector with elements, and you know the starting and ending points, but not
the exact spacing, you can use the linspace command. It has the syntax:

The increment is automatically computed and is equal to:

v18 = linspace(5, 8, 31)

v18 = 1×31
5.0000 5.1000 5.2000 5.3000 5.4000 5.5000 5.6000 ⋯

The above command is similar to:

v19 = [5:0.1:8]

v19 = 1×31
5.0000 5.1000 5.2000 5.3000 5.4000 5.5000 5.6000 ⋯

In engineering problems, sometimes we need entries with logarithmic spacing instead of regular
(fixed) spacing. In this case, we can use the logspace command. By default, this command creates
For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 6 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

elements unless the number of entries is specified. The elements lie between and ,
where and are user defined.

v20 = logspace(1,5) % creates 50 elements between 10 and 100000

v20 = 1×50
105 ×
0.0001 0.0001 0.0001 0.0002 0.0002 0.0003 0.0003 ⋯

Notice that the above command provides the results in engineering notation misleading you to think
that some elements are identical (e.g., 0.0001). In fact, if you change the display format to long you
will see more digits of the generated number.

v21 = logspace(1,5, 5) % creates 5 elements between 10 and 100000

v21 = 1×5
10 100 1000 10000 100000

Matrices
MATLAB matrices are similar in notion to 2D matrices in C++ and Java; albeit, much simpler to use.
A matrix consists of both rows and columns. Therefore, a vector is a special case of a matrix that
has either one row or one column.

To create a matrix in MATLAB, elements of each row are separated by a comma (,), and rows are
separated by a semicolon. To save this matrix into variable :

M = [2 4 10 3; -9 0 6 7; 1 4 12 6]

M = 3×4
2 4 10 3
-9 0 6 7
1 4 12 6

You can retrieve the dimensions of the matrix by using the size function. It will return the number of
rows and column, respectively. In this case, the size of is 3x4.

size(M)

ans = 1×2
3 4

To retrieve the total number of elements in the matrix, use the numel command (short for number of
elements). You can use this command with vectors as well, and in this specific case it will be
equivalent to the length command .

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 7 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

numel(M)

ans = 12

Suppose we have two matrices:

K = [1, 4, 6, 3 ; -6, 0, 6, 7]

K = 2×4
1 4 6 3
-6 0 6 7

L = [2, 5, 17, 8; -1, 4, 4, 0]

L = 2×4
2 5 17 8
-1 4 4 0

You can concatenate the two matrices horizontally or vertically only if they match each other in the
number of elements along the side you wish to concatenate them in.

We can concatenate matrices and vertically in three different ways:

V1 = [K; L] % Using the semicolon

V1 = 4×4
1 4 6 3
-6 0 6 7
2 5 17 8
-1 4 4 0

V2 = vertcat(K, L) % Using the explicit vertical concatenation

V2 = 4×4
1 4 6 3
-6 0 6 7
2 5 17 8
-1 4 4 0

V3 = cat(1,K,L) % Using the generic concatenate function. 1 means


vertical concatenate, 2 horizontal

V3 = 4×4
1 4 6 3
-6 0 6 7
2 5 17 8
-1 4 4 0

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 8 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

We can concatenate matrices and horizontally in three different ways:

H1 = [K, L] % Using the colon

H1 = 2×8
1 4 6 3 2 5 17 8
-6 0 6 7 -1 4 4 0

H2 = horzcat(K, L) % Using the explicit horizontal concatenation

H2 = 2×8
1 4 6 3 2 5 17 8
-6 0 6 7 -1 4 4 0

H3 = cat(2,K,L) % Using the generic concatenate function. 1 means


vertical concatenate, 2 horizontal

H3 = 2×8
1 4 6 3 2 5 17 8
-6 0 6 7 -1 4 4 0

Vector and Matrix Indexing and Addressing

The most important rule which you must never forget is that MATLAB indices always start from
ONE, not 0.

myVector = [2 : 0.5: 5]

myVector = 1×7
2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000

To access the first, fifth, and last elements in this vector, one can write:

myVector(1)

ans = 2

myVector(5)

ans = 4

myVector(numel(myVector))

ans = 5

You can retrieve any element in an array either using linear indexing or subscript indexing. In
linear indexing, you can think of the array as consecutive columns whose elements are numbered
from 1 to . Subscript indexing is similar to the one you use in C++ and Java, with the only
difference that indices start from 1 not 0.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 9 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

So, in the previous example with the matrices and , one can access the element 0 in matrix
by either:

K(4)

ans = 0

K(2,2)

ans = 0

To replace the last element in matrix by 5, one can write:

L(numel(L)) = 5

L = 2×4
2 5 17 8
-1 4 4 5

L(2,4) = 5

L = 2×4
2 5 17 8
-1 4 4 5

The colon (:) operator is used to access a range of indices. For example, to retrieve all elements in
matrix , one can write:

K(:)

ans = 8×1
1
-6
4
0
6
6
3
7

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 10 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

To retrieve only the second row in matrix , one can write:

K(2, :) % This means access the second row, and retrieve all its elements.

ans = 1×4
-6 0 6 7

To retrieve the middle two columns in array :

K(:, 2:3)

ans = 2×2
4 6
0 6

This means access all columns from 2 to 3, and retrieve all rows.

To delete the last column in matrix , one can write:

disp(L)

2 5 17 8
-1 4 4 5

L(:, 4) = []

L = 2×3
2 5 17
-1 4 4

This means, delete all elements in the fourth column.

Suppose the matrix A is given as:

A = [21, 53, 17, 58, 60; ...


17, 48, 94, 70, 99; ...
15, 44, 14, 37, 19; ...
68, 78, 88, 80, 15; ...
11, 58, 77, 10, 23; ...
32, 26, 78, 79, 10]

A = 6×5
21 53 17 58 60
17 48 94 70 99
15 44 14 37 19

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 11 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

68 78 88 80 15
11 58 77 10 23
32 26 78 79 10

To access the inner elements without the border elements, one can write:

A(2:5, 2:4)

ans = 4×3
48 94 70
44 14 37
78 88 80
58 77 10

Also note how we used the ellipses (...) to write the array in a more eye-friendly way.

Special MATLAB Vectors and Matrices

MATLAB has functions to create special vectors and matrices that are useful in many instances.

The first matrix is an ALL-ones matrix. A matrix whose elements are initialized to the value 1. The
second matrix is an ALL-zeros matrix whose elements are initialized to the value of 0.

You can create row vectors, column vectors, or matrices by passing the number of rows and
columns to the function. If you pass one argument , the function will generate a square matrix of
size .

ones(1,4)

ans = 1×4
1 1 1 1

ones (3,1)

ans = 3×1
1
1
1

ones(2,3)

ans = 2×3
1 1 1
1 1 1

ones(3) % Supplying one input n creates a square array of that number nxn

ans = 3×3
1 1 1
1 1 1
1 1 1

You can do the same as above using the zeros function:

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 12 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

zeros(1,4)

ans = 1×4
0 0 0 0

zeros (3,1)

ans = 3×1
0
0
0

zeros(2,3)

ans = 2×3
0 0 0
0 0 0

zeros(3) % Supplying one input n creates a square array of that number nxn

ans = 3×3
0 0 0
0 0 0
0 0 0

The identity matrix is a matrix whose diagonal is ones while all other elements are zero. Remember,
that multiplying any SQAURE matrix with a SQAURE identity matrix results in the same original
matrix. Use the eye function to create identity matrices.

eye (4)

ans = 4×4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

You can also create rectangular identity matrices. In these matrices, columns whose elements don't
fall on the diagonal are zeroed out.

eye(2, 3)

ans = 2×3
1 0 0
0 1 0

Block diagonal matrices combine multiple arrays together but aligns them diagonally. All remaining
empty matrix locations are filled with zero. To do this in MATLAB:

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 13 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

A1 = ones(2,2);
A2 = 2*ones(3,2);
A3 = 3*ones(2,3);
B = blkdiag(A1,A2,A3)

B = 7×7
1 1 0 0 0 0 0
1 1 0 0 0 0 0
0 0 2 2 0 0 0
0 0 2 2 0 0 0
0 0 2 2 0 0 0
0 0 0 0 3 3 3
0 0 0 0 3 3 3

A magic matrix is a special matrix with interesting mathematical properties:

• It is a square matrix of size , and


• All elements in the matrix fall between 1 and
• All rows and all column elements sum to the same value

magic(3)

ans = 3×3
8 1 6
3 5 7
4 9 2

Matrix Manipulation

Similar to vectors, you can perform the matrix transpose operation where rows become columns.

For example:

M = [2 4 10 3; -9 0 6 7; 1 4 12 6]

M = 3×4
2 4 10 3
-9 0 6 7
1 4 12 6

And one can obtain its transpose as:

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 14 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

transpose(M)

ans = 4×3
2 -9 1
4 0 4
10 6 12
3 7 6

or simply by using the (') operator:

M'

ans = 4×3
2 -9 1
4 0 4
10 6 12
3 7 6

If you have a matrix and wish to create another matrix out of its replicas, you can use the repmat
command. In this command, you specify how many times is the matrix replicated horizontally, then
vertically, respectively.

repmat(M, 2, 3)

ans = 6×12
2 4 10 3 2 4 10 3 2 4 10 3
-9 0 6 7 -9 0 6 7 -9 0 6 7
1 4 12 6 1 4 12 6 1 4 12 6
2 4 10 3 2 4 10 3 2 4 10 3
-9 0 6 7 -9 0 6 7 -9 0 6 7
1 4 12 6 1 4 12 6 1 4 12 6

A similar command is repeat elements repelem. It works on vectors and matrices.

Suppose we have a small vector of three values and you wish to repeat each element
three times:

repelem([1, 0.5 0], 3)

ans = 1×9
1.0000 1.0000 1.0000 0.5000 0.5000 0.5000 0
0 0

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 15 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

To repeat each element in matrix three times horizontally, and two times vertically, one can write:

repelem(M,3,2)

ans = 9×8
2 2 4 4 10 10 3 3
2 2 4 4 10 10 3 3
2 2 4 4 10 10 3 3
-9 -9 0 0 6 6 7 7
-9 -9 0 0 6 6 7 7
-9 -9 0 0 6 6 7 7
1 1 4 4 12 12 6 6
1 1 4 4 12 12 6 6
1 1 4 4 12 12 6 6

You can reshape a matrix by using the reshape command which takes in as input a matrix, and the
dimensions of its new shape.

reshape(M, 6, 2)

ans = 6×2
2 10
-9 6
1 12
4 3
0 7
4 6

However, the number of elements in the new shape must be the same as in the old matrix.
Otherwise, MATLAB will issue an error.

reshape(M, 5, 3) % No. of elements 15 instead of 12, FAIL

The command circshift (A, K, dim) circularly shifts the elements in matrix A by K positions. The
parameter dim specifies if one wishes to do the circular shift on the rows (dim = 1), or columns (dim
= 2). These are the rules of how this command works:

• If K is positive, dim = 1, rows move downward


• If K is negative, dim = 1, rows move upward
• If K is positive, dim = 2, columns move left
• If K is negative, dim = 2, columns move right

circshift(M, 1, 1)

ans = 3×4
1 4 12 6
2 4 10 3
-9 0 6 7
For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 16 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

circshift(M, -1, 1)

ans = 3×4
-9 0 6 7
1 4 12 6
2 4 10 3

circshift(M, 1, 2)

ans = 3×4
3 2 4 10
7 -9 0 6
6 1 4 12

circshift(M, -1, 2)

ans = 3×4
4 10 3 2
0 6 7 -9
4 12 6 1

You can rotate any vector or matrix counter-clockwise by or its multiples by using the rot90
command:

rot90(M, 1) % Rotate M counter-clockwise by 90 degrees

ans = 4×3
3 7 6
10 6 12
4 0 4
2 -9 1

rot90(M, 3) % Rotate M counter-clockwise by 90 x 3 = 270 degrees

ans = 4×3
1 -9 2
4 0 4
12 6 10
6 7 3

You can flip arrays either around their central row or column using two flip commands:

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 17 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

fliplr(M) % Flip array left to right

ans = 3×4
3 10 4 2
7 6 0 -9
6 12 4 1

flipud(M) % Flip array yp to down

ans = 3×4
1 4 12 6
-9 0 6 7
2 4 10 3

To extract the diagonal elements of the matrix, simply use the diag command:

diag(M)

ans = 3×1
2
0
12

Sorting Vectors and Matrices

sort(A) sorts the elements of vector or matrix A in ascending order.

• If A is a vector, then sort(A) sorts the vector elements.


• If A is a matrix, then sort(A) treats the columns of A as vectors and sorts each column.

sort(M)

ans = 3×4
-9 0 6 3
1 4 10 6
2 4 12 7

To sort the elements in each row, simply sort the transpose of a matrix:

sort(M')

ans = 4×3
2 -9 1
3 0 4
4 6 6
10 7 12

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 18 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

To sort the elements in descending order, the command slightly changes to sort(A,'descend')

sort(M,'descend')

ans = 3×4
2 4 12 7
1 4 10 6
-9 0 6 3

Finally, an interesting sorting command is sortrows. Unlike the sort command, this command sorts
the entire row block based on the values of the first column. If there is a tie, it decides based on the
values of the second column, and so.

sortrows(M)

ans = 3×4
-9 0 6 7
1 4 12 6
2 4 10 3

Vector and Matrix Mathematical Operations

The beauty of MATLAB is that it allows quick mathematical and logical operations on vectors and
matrices.

Again, suppose we have the previous two matrices and a third square matrix:

K = [1, 4, 6, 3 ; -6, 0, 6, 7]

K = 2×4
1 4 6 3
-6 0 6 7

L = [2, 5, 17, 8; -1, 4, 4, 0]

L = 2×4
2 5 17 8
-1 4 4 0

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 19 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

P = [5, 7; 8, 1]

P = 2×2
5 7
8 1

To add or subtract them together on an element-by-element basis, you simply write:

K + L

ans = 2×4
3 9 23 11
-7 4 10 7

K - L

ans = 2×4
-1 -1 -11 -5
-5 -4 2 7

We know from mathematics that matrix multiplication is different than regular multiplication. You
cannot multiply any two matrices together unless they satisfy a matrix dimension restriction:

That is the number of columns of the first array equals the number of rows in the second array. For
example, we cannot perform matrix multiplication on the arrays K and L above as MATLAB will give
an error because the size of each is .

K * L % Error using * Incorrect dimensions for matrix


multiplication.

Yet, multiplying K by the transpose of L works fine because K has a size of , the transpose of L
has the size of , and the result will have a size of .

K * L'

ans = 2×2
148 39
146 30

Remember matrix multiplication is not commutative. . So, multiplying the transpose of L by


K in this order will give a totally different result:

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 20 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

L' * K

ans = 4×4
8 8 6 -1
-19 20 54 43
-7 68 126 79
8 32 48 24

But what if you wish to do element-by-element multiplication, and not matrix multiplication. In this
case, you must precede the * operator by a dot, so we have a new operator (.*)

K .* L

ans = 2×4
2 20 102 24
6 0 24 0

To do element-by-element operations on matrices, you must precede any operator by a dot. For
example, dividing each element by 8:

K ./ 8

ans = 2×4
0.1250 0.5000 0.7500 0.3750
-0.7500 0 0.7500 0.8750

Or raising each element to a power of 2 or 4:

K .^ 2

ans = 2×4
1 16 36 9
36 0 36 49

K .^ 4

ans = 2×4
1 256 1296 81
1296 0 1296 2401

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 21 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

However, if you write:

K ^ 2

It will flag an error because this means you are multiplying and their dimensions do not agree.
You can only do this with square matrices:

P ^ 2

ans = 2×2
81 42
48 57

P ^ 4

ans = 2×2
8577 5796
6624 5265

What if the array elements are the powers that you wish to raise a scalar to, say we want to raise the
number 4 to the power of elements in matrix .

4 .^ K

ans = 2×4
0.0004 0.0256 0.4096 0.0064
0.0000 0.0001 0.4096 1.6384

You cannot raise a matrix to a matrix:

K ^ P % Wrong

What if you want to multiply the square root of each element in array by the of each
corresponding element in array :

sqrt(K) .* log10(L)

ans = 2×4
0.3010 1.3979 3.0140 1.5642
-3.3420 0 1.4747 -Inf

In linear algebra courses, you learnt of the inverse of a matrix. MATLAB has a special inverse
function called inv. One can compute the inverse of a matrix only if it is square.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 22 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

This would not work:

inv(K)
inv(L)

But this does:

inv(P)

ans = 2×2
-0.0196 0.1373
0.1569 -0.0980

A very useful command is the sum command. It sums all the values in a vector, or if the input is a
matrix, it sums all the values in each column.

sum([7 8 9 5 0])

ans = 29

sum(K)

ans = 1×4
-5 4 12 10

Another useful command is the prod command. It multiplies all the values in a vector, or if the input
is a matrix, it multiplies all the values in each column.

prod([7 8 9 5 1])

ans = 2520

prod(K)

ans = 1×4
-6 0 36 21

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 23 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

Vector and Matrix Logical Operations

Like all other programming languages, MATLAB supports logical and relational operators. We list
them in the following table.

When you use these operations, the output is either 0 (false) or 1 (true). These are not numeric or
, but logical values. In the same way, if we compare matrices using relational operators, the output
matrix of s and s is not numeric, but logical.

These operators work on an element-by-element basis.

Again, suppose we have:

K = [1, 4, 6, 3 ; -6, 0, 6, 7]

K = 2×4
1 4 6 3
-6 0 6 7

L = [2, 5, 17, 8; -1, 4, 4, 0]

L = 2×4
2 5 17 8
-1 4 4 0

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 24 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

One can check if each element in K is less than each corresponding element in L by writing:

R = K < L

R = 2×4 logical array


1 1 1 1
1 1 0 0

Check for the type (class) of the resulting matrix by typing:

whos R

Name Size Bytes Class Attributes

R 2x4 8 logical

You can extract the numbers that meet a specific criterion using relational operators easily. For
example, to store the numbers that are less than in array in a new matrix, simply write:

Q = K(K < 5)

Q = 5×1
1
-6
4
0
3

The step K < 5 first compares each element in K if it is less than five or not and it returns a logical
array of 0’s and 1’s. This array is passed to K () which retrieves the corresponding elements for each
one that appears in the logical array.

If you want to retrieve the linear index of the elements that are less than in array , use the find
function:

find(K < 5)

ans = 5×1
1
2
3
4
7

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 25 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

The step K < 5 first compares each element in K if it is less than five or not and it returns a logical
array of 0’s and 1’s. This array is passed to the find function which retrieves the linear index for
each one that appears in the logical array.

Multidimensional Matrices

3D matrices consist of pages of 2D matrices. Suppose one has:

and that we wish to store them as a 3D matrix of three pages as follows:

One can construct a 3D matrix by first storing the 2D matrices, then appending them:

A = [5, 7; 8, 1]

A = 2×2
5 7
8 1

B = [1, 4; 7, 1]

B = 2×2
1 4
7 1

C = [0, 9; 4, 3]

C = 2×2
0 9
4 3

A (:, :, 2) = B

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 26 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

A =
A(:,:,1) =

5 7
8 1

A(:,:,2) =

1 4
7 1

The previous commands append the second array B to the first array A creating a 3D array.

A (:, :, 3) = C

A =
A(:,:,1) =

5 7
8 1

A(:,:,2) =

1 4
7 1

A(:,:,3) =

0 9
4 3

The previous commands append the second array C to the 2D array of A and B expanding the 3D
array.

Addressing 3D matrices is simple. As before, using subscript addressing, define the row and
column location in this respective order, then finally specify the page.

For example, to retrieve the number on the third page:

A(1,2,3)

ans = 9

To get the whole second page:

A(:, :, 2)

ans = 2×2
1 4
7 1

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 27 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

Data Import and Pre-processing


MATLAB has extremely powerful tools to import and export data whether it is text, spreadsheets,
audio, video, images, or data stored in special scientific formats. In this experiment, we will focus on
local MATLAB files (.mat), text files (.txt, .csv), and spreadsheets (.xls, .xlsx).

Loading and Storing MATLAB Variables


You can save all your workspace variables that you have created in a MATLAB session into a
special file with the extension .mat. You can load these variables again at the start of your next
session and start from where you last stopped. This is done through the simple save and load
commands. You must specify a file name (as a string or character array), and optionally followed by
the names of the variables you want to save/load. If you do not specify any variables, the commands
will save or load ALL variables.

save("exp3_all_variables.mat")
save('exp3_some_variables.mat', "s1", "s2", "s3")

But where are your variables stored? The variables are stored in the current working path. You can
see the working path right under the ribbon (and you can change it from there too). Alternatively, you
can write the "print working directory" command:

pwd

ans = 'D:\Google Drive\UJ-Courses\CPE213-Numerical_Analysis\Experiments'

To load your MATLAB work session variables, use the load command which has an identical
syntax.

load("exp3_all_variables.mat")
load('exp3_some_variables.mat', "s1", "s2", "s3")

Using the Interactive Import Tool


Many times, numeric data is stored in textfiles or Excel spreadsheets. You can use MATLAB
commands that we introduced in the previous section. However, if you are working with one or two
files, then you can use MATLAB's Import Data tool to import data into MATLAB's workspace using
a GUI tool.

1. You can access the tool from the Home ribbon, then Import tool.
2. A simple Open File window will pop out, choose the file you want to import (.txt, .csv.
.xlsx, ... etc). There are different options for Spreadsheets and Text Files
3. A new Import screen opens where you select the import settings. Basically, the settings are
identical, except for text files, you get the extra option to choose the delimiter that splits the
data into columns.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 28 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

Importing Spreadsheets using the GUI tool

1. By default, it selects the entire range of the spreadsheets' cells. You can change the range to
import a subset of this range.
2. Specify the row number that holds the text data (e.g., Column headings). This helps
MATLAB exclude it if you are importing it into a numeric array.
3. Always make sure to import your data into a Numeric matrix, or a String Array if you want
to import the data as text.
4. Choose the import behaviour if your input data has problems, say if it has empty cells, or
characters instead of numbers. You can replace these values with NaN or write any other
value you want, or you can exclude the rows or columns that has these erroneous cells. It all
depends on your application and what you want to do.
5. Once you are done, click Import Selection, you can either simply save the data or generate
the commands that import the data.

Importing Text Files using the GUI Tool

1. By default, the tool will try to find the delimiter (space, tab, comma ... etc) that best separates
the text file into columns.
2. You can select the entire range of the data, or you can change the range to import a subset
of this range.
3. Specify the row number that holds the text data (e.g., Column headings). This helps
MATLAB exclude it if you are importing it into a numeric array.
4. Always make sure to import your data into a Numeric matrix, or a String Array if you want
to import the data as text.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 29 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

5. Choose the import behaviour if your input data has problems, say if it has empty cells, or
characters instead of numbers. You can replace these values with NaN or write any other
value you want, or you can exclude the rows or columns that has these erroneous cells. It all
depends on your application and what you want to do.
6. Once you are done, click Import Selection, you can either simply save the data or generate
the commands that import the data.

It is worth noting that the GUI import tool can be used to import many other data formats such as
audio and video files, different types of images and other datafiles.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 30 of 31
Copyright © (2020) Dr. Ashraf Suyyagh – All Rights Reserved

Experiment version 1.2


Original Experiment October 5th, 2020
Last Updated March 11th, 2022
Dr. Ashraf Suyyagh - All Rights Reserved

Revision History

Ver. 1.2
Moved the Data Import and Pre-processing Part from the old Fundamentals III
into this experiment
Ver. 1.1
Corrected formatting and spelling mistakes.
Corrected the equation that computes the number of generated elements in a
vector by added the floor symbol.
Added more info about the display format of the logspace command.
Added more clarification on retrieving values or indices using logical
operations.
Added more clarification to appending 2D arrays to form 3D arrays.

For Internal Use Only at the Department of Computer Engineering – University of Jordan Page 31 of 31

You might also like