You are on page 1of 42

Week 02:

1 - Vector and Matrices


2 – Graphs and Plots in MATLAB
Applied Numerical Methods and
Programming in Engineering
1 – Vector and Matrices
› One of the main features and advantages of MATLAB is
the handling of vectors, arrays, and matrices.
› Vectors, arrays, and matrices play a great role in solving
mathematical problems numerically.
– They are used to store sets of values, all of which are of the
same type.

› Array is the most fundamental data type in MATLAB.


– In MATLAB, arrays are a collection of several values of the same
type that are represented by a single variable.
› The string and number data type are particular cases of arrays.

DR. MOHAMAD A. ALKHALIDI 2


1 – Vector and Matrices
› A matrix can be visualized as a table of values.
– The dimensions of a matrix are r x c, where r is the number of
rows and c is the number of columns.
› A one column or row array is known as a vector (one
dimensional array).
– A vector can be either a row vector or a column vector.
– a vector has n elements,
› a row vector would have the dimensions 1 x n, and
› a column vector would have the dimensions n x 1.
– A scalar (one value) has the dimensions 1 x 1 (an array with one
row and one column).
– Vectors and scalars are special cases of matrices.

DR. MOHAMAD A. ALKHALIDI 3


1 – Vector and Matrices

7 2 10 8 7 17 26 4 3 1 2
3
Scalar 1x9
4 vector
5 1 2 3 4
6 56 6 9 4
3 90 8 10
5x1
vector
3x4
Matrix
All the values stored in these matrices are stored in what are called elements.

DR. MOHAMAD A. ALKHALIDI 4


1 – Vector and Matrices
› A row array is created using comma separated values inside
brackets:
– >> x = [0, 1, 4, 5]
› A column array is created using semicolons to separate
values:
– >> x = [0; 1; 4; 5]
› Matrix is declared with commas (or spaces) separating
columns, and semicolons separating rows:
– >> x = [1, 2, 3; 4, 5, 6; 7, 8,9]
› When declaring Matrix (2D array) in MATLAB all rows and all columns need
have same size. If not, an error message will be generated.
– x = [1, 2, 3; 4, 5]
Error using vertcat
Dimensions of arrays being concatenated are not consistent.

DR. MOHAMAD A. ALKHALIDI 5


1 – Vector and Matrices
› Iterators can be used for the values in the rows using the
colon operator:
– X = [12:19;22:29]
› You can create matrices of random numbers using the
function rand:
– X = rand(n) will create n x n random number matrix
– X = rand(n,m) will create n x m random number matrix.
› You also can create matrices of random integers can be
generated using randi, but you must specify the range of the
random numbers also
– randi([10 50],4)
– randi([10 50],4,5)

DR. MOHAMAD A. ALKHALIDI 6


1 – Vector and Matrices
› Special Matrices:
– zeros: Create array of all zeros
› X = zeros(n) returns an n-by-n matrix of zeros.
– zeros(5) create a 5-by-5 matrix of zeros
› >> X = zeros(5)
› X = zeros(sz1,...,szN) returns a sz1-by-...-by-szN array of zeros where sz1,...,szN indicate
the size of each dimension.
– zeros(2,3) returns a 2-by-3 matrix of zeros
› >> X = zeros(2,3)
– Ones: Create arrays of all ones
› X = ones(n) returns an n-by-n matrix of ones
– ones(4) create 4-by-4 matrix of ones
› >> X = ones(4)
› X = ones(sz1,...,szN) returns a sz1-by-...-by-szN array of ones where sz1,...,szN indicate
the size of each dimension.
– ones(4,5) returns a 4-by-5 matrix of ones
› >> X = ones(4,5)

DR. MOHAMAD A. ALKHALIDI 7


1 – Vector and Matrices
› Special Matrices:
– eye: Create Identity matrix
› X = eye(n) returns an n-by-n identity matrix with ones on the main diagonal
and zeros elsewhere.
– Example: eye(3) create a 3-by-3 identity matrix
› >> X = eye(3)
› X = eye(n, m) returns an n-by-m matrix with ones on the main diagonal and
zeros elsewhere.
› >> X = eye(4,5)

DR. MOHAMAD A. ALKHALIDI 8


1 – Vector and Matrices
› Referring to and Modifying Matrix Elements
– To refer to matrix elements, the row and then the column
subscripts are given in parentheses (always the row first and
then the column).
› This is called subscripted indexing; it uses the row and column subscripts
– For example:
› X = [2:4; 3:5] will creates a matrix variable X
› X(2,3) refers to the value in the second row, third column of X:
X=

2 3 4
3 4 5

>> X(2,3)

ans =

5 DR. MOHAMAD A. ALKHALIDI 9


1 – Vector and Matrices
› Referring to and Modifying Matrix Elements
– We can also refer to a subset of a matrix:
› X(1:2,2:3)
– Using just one colon by itself for the row subscript means all
rows.
› X(:,2)
– Using just one colon for the column subscript means all
columns.
› X(1,:)

DR. MOHAMAD A. ALKHALIDI 10


1 – Vector and Matrices
› Referring to and Modifying Matrix Elements
– linear indexing: If a single index is used with a matrix, MATLAB
unwinds the matrix column by column.
› X(3)
› In general, it is recommended working with matrices to use subscripted
indexing
– Changing matrix values:
› An individual element in a matrix can be modified by assigning a new value
to it.
– X(2,3) = 10
› Also, we can change an entire row or column
– X(:,3) = 8
– X(2,:) = 1:3

DR. MOHAMAD A. ALKHALIDI 11


1 – Vector and Matrices
› Matrix Concatenation:
– You can use square brackets to join existing matrices together. This way of creating a matrix is called concatenation. For
example,
› >> a = zeros(4);
› >> b = ones(4);
› >> c = [a, b]
c=
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
0 0 0 0 1 1 1 1
>> c = [a; b]
c=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

DR. MOHAMAD A. ALKHALIDI 12


1 – Vector and Matrices
› Extend a matrix:
– To extend a matrix an individual element can not be added as
that would mean there would no longer be the same number of
values in every row.
– However, an entire row or column could be added.
› For example, the following would add a fourth column to the matrix
created previously.
› X(:,4)=[9 2]’
– If there is a gap between the current matrix and the row or
column being added, MATLAB will fill in with zeros.
› X(4,:) =2:2:8

DR. MOHAMAD A. ALKHALIDI 13


1 – Vector and Matrices
› Dimensions:
– The length and size functions in MATLAB are used to find dimensions
of vectors and matrices.
› The length function returns the number of elements in a vector.
› The size function returns the number of rows and columns in a vector or
matrix.
– For example, Z = -2:1 has four elements, so its length is 4 and its size is 1 x 4
› The size function returns the number of rows and then the number of
columns,
– To capture these values in separate variables, use a vector of variables (two) on the
left of the assignment. The variable r stores the first value returned, which is the
number of rows, and c stores the number of columns.
› [r, c] = size (X)
› For a matrix, the length function will return either the number of rows or the
number of columns, whichever is largest.

DR. MOHAMAD A. ALKHALIDI 14


1 – Vector and Matrices
› Dimensions:
– The function numel returns the total number of elements in any
array (vector or matrix).
› For vectors, numel is equivalent to the length of the vector.
› For matrices, it is the product of the number of rows and columns.

– The built-in expression end can be used to refer to the last


element in a vector or to the last row or column.

DR. MOHAMAD A. ALKHALIDI 15


1 – Vector and Matrices
› Magic square:
– magic(n) returns an n-by-n matrix constructed from the integers
1 through n2 with equal row and column sums.
– The order n must be a scalar greater than or equal to 3 in order
to create a valid magic square
› >> A = magic(5)
A=

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
DR. MOHAMAD A. ALKHALIDI 16
1 – Vector and Matrices
› Transposing and flipping matrices:
– A common task in linear algebra is to work with the transpose of
a matrix, which turns the rows into columns and the columns
into rows.
› To do this, use the transpose function or the .' operator.
– A = [8 1 6;3 5 7;4 9 2] A=

8 1 6
3 5 7
4 9 2

– B = A .’ >> B = A.'

B=

8 3 4
1 5 9
6 7 2 DR. MOHAMAD A. ALKHALIDI 17
1 – Vector and Matrices
› Changing Dimensions:
– To change the dimensions or configuration of matrices ( or in
many cases vectors), MATLAB has the following famous built-in
functions:
› reshape: changes the dimensions of a matrix,
› flipud: flips the rows of a matrix in an up-to-down direction, and
› fliplr: flips the columns in a left-to-right direction.
› flip: flips any array; it flips a vector (left to right if it is a row vector or up to
down if it is a column vector) or a matrix (up to down by default)
› rot90: rotates the matrix counterclockwise 90 degrees
› repmat: Repeat copies of array.

DR. MOHAMAD A. ALKHALIDI 18


1 – Vector and Matrices
› Changing Dimensions:
– reshape:
› B = reshape(A,sz) reshapes A using the size vector, sz, to define size(B).
– For example, reshape(A,[2,3]) reshapes A into a 2-by-3 matrix.
– sz must contain at least 2 elements, and prod(sz) must be the same as
numel(A).
› B = reshape(A,sz1,...,szN) reshapes A into a sz1-by-...-by-szN array where
sz1,...,szN indicates the size of each dimension.
– You can specify a single dimension size of [] to have the dimension size
automatically calculated, such that the number of elements in B matches the
number of elements in A.
› For example, if A is a 10-by-10 matrix, then reshape(A,2,2,[]) reshapes the
100 elements of A into a 2-by-2-by-25 array.

DR. MOHAMAD A. ALKHALIDI 19


1 – Vector and Matrices
› Changing Dimensions:
› Reshape a 1-by-10 vector into a 5-by-2 matrix.
– A = 1:10;
– B = reshape(A,[5,2])
– B = 5×2
› Reshape a 4-by-4 square matrix into a matrix that has 2 columns. Specify
[] for the first dimension to let reshape automatically calculate the
appropriate number of rows.
– A = magic(4);
– B = reshape(A,[],2)
› Reshape a 3-by-2-by-3 array of zeros into a 9-by-2 matrix.
– A = zeros(3,2,3);
– B = reshape(A,9,2)

DR. MOHAMAD A. ALKHALIDI 20


1 – Vector and Matrices
› Changing Dimensions:
– flipud: flips the rows of a matrix in an up-to-down direction, and
– fliplr: flips the columns in a left-to-right direction.
>> B = flipud(A) >> C = fliplr(A)

B= C=

11 18 25 2 9 15 8 1 24 17
10 12 19 21 3 16 14 7 5 23
4 6 13 20 22 22 20 13 6 4
23 5 7 14 16 3 21 19 12 10
17 24 1 8 15 9 2 25 18 11

DR. MOHAMAD A. ALKHALIDI 21


1 – Vector and Matrices
› Changing Dimensions:
› B = repmat(A,n) returns an array containing n copies of A in the row and
column dimensions. The size of B is size(A)*n when A is a matrix.
› B = repmat(A,r1,...,rN) specifies a list of scalars, r1,..,rN, that describes how
copies of A are arranged in each dimension. When A has N dimensions,
the size of B is size(A).*[r1...rN]. For example, repmat([1 2; 3 4],2,3) returns
a 4-by-6 matrix.
› B = repmat(A,r) specifies the repetition scheme with row vector r. For
example, repmat(A,[2 3]) returns the same result as repmat(A,2,3).

DR. MOHAMAD A. ALKHALIDI 22


2 – The Colon Operator
› The colon operator is a powerful tool for creating and
manipulating arrays.
› If a colon is used to separate two numbers, MATLAB generates
the numbers between them using an increment of one:
– >> t = 1:5
t=
1 2 3 4 5
› If colons are used to separate three numbers, MATLAB
generates the numbers between the first and third numbers
using an increment equal to the second number:
– >> t=1:0.5:3
t=
1.0000 1.5000 2.0000 2.5000 3.0000

DR. MOHAMAD A. ALKHALIDI 23


2 – The Colon Operator
› Negative increments can also be used
– >> m = 5:-1.5:0.5
m=
5.0000 3.5000 2.0000 0.5000

› Aside from creating series of numbers, the colon can also


be used as a wildcard to select the individual rows and
columns of a matrix. When a colon is used in place of a
specific subscript, the colon represents the entire row or
column.
› You can also use the colon notation to selectively extract
a series of elements from within an array.
DR. MOHAMAD A. ALKHALIDI 24
3 – The linspace and logspace Functions
› Linspace generate linearly spaced vector
– Syntax
› y = linspace(x1,x2)
› y = linspace(x1,x2,n)
– y = linspace(x1,x2) returns a row vector of 100 evenly spaced points
between x1 and x2.
– y = linspace(x1,x2,n) generates n points. The spacing between the
points is (x2-x1)/(n-1).

› linspace is similar to the colon operator, “:”, but gives direct


control over the number of points and always includes the
endpoints.
– “lin” in the name “linspace” refers to generating linearly spaced
values.

DR. MOHAMAD A. ALKHALIDI 25


3 – The linspace and logspace Functions
› logspace generate logarithmically spaced. The logspace
function is especially useful for creating frequency
vectors. The function is the logarithmic equivalent of
linspace and the ‘:’ operator.
– Syntax
› y = logspace(a,b): generates a row vector y of 50 logarithmically spaced
points between decades 10^a and 10^b.
› y = logspace(a,b,n): generates n points between decades 10^a and 10^b
› y = logspace(a,pi): generates 50 points between 10^a and pi, which is
useful in digital signal processing for creating logarithmically spaced
frequencies in the interval [10^a,pi].
› y = logspace(a,pi,n): generates n points between 10^a and pi.

DR. MOHAMAD A. ALKHALIDI 26


4 – Character Strings
› Aside from numbers, alphanumeric information or
character strings can be represented by enclosing the
strings within single/double quotation marks.
– For example,
› >> f = 'Miles ';
› >> s = 'Davis';
› Each character in a string is one element in an array.
Thus, we can concatenate (i.e., paste together) strings as
in
– >> x = [f s]
› x=
– Miles Davis

DR. MOHAMAD A. ALKHALIDI 27


4 – Character Strings
› Note that very long lines can be continued by placing an
ellipsis (three consecutive periods) at the end of the line to be
continued.
– For example, a row vector could be entered as
› >> a = [1 2 3 4 5 ...
› 6 7 8]
– a=
› 12345678
– However, you cannot use an ellipsis within single quotes to continue a
string.
– To enter a string that extends beyond a single line, piece together
shorter strings as in
› >> quote = ['Any fool can make a rule,' ...
› ' and any fool will mind it']
› quote =
– Any fool can make a rule, and any fool will mind it

DR. MOHAMAD A. ALKHALIDI 28


4 – Character Strings
› If the text includes double quotes, use two double quotes
within the definition.
– q = "Something ""quoted"" and something else.“
› q=
– "Something "quoted" and something else."

› To add text to the end of a string, use the plus operator,


+.
– >> f = 71;
– >> c = (f-32)/1.8;
– >> tempText = "Temperature is " + c + "C“
› tempText =
– "Temperature is 21.6667C"

DR. MOHAMAD A. ALKHALIDI 29


4 – Character Strings
› Similar to numeric arrays, string arrays can have multiple
elements. Use the strlength function to find the length of
each string within an array.
– >> A = ["a","bb","ccc"; "dddd","eeeeee","fffffff"]
› A=
– 2×3 string array
"a" "bb" "ccc"
"dddd" "eeeeee" "fffffff"
› >> strlength(A)
– ans =
› 1 2 3
› 4 6 7

DR. MOHAMAD A. ALKHALIDI 30


5 - Graphs & Plots in MATLAB
› Another extradentary feature in MATLAB is that it has
many 2D and 3D graphing capabilities.

– Typing help graph2d in the command widows of MATLAB would


display some of the two-dimensional graph functions, as well as
functions to manipulate the axes and to put labels and titles on
the graphs.

– The Search Documentation under MATLAB Graphics also has a


section on two- and three-dimensional plots.

DR. MOHAMAD A. ALKHALIDI 31


5 - Graphs & Plots in MATLAB
› The Plot function:
– The plot function 2-D line plot.
› plot(X,Y) creates a 2-D line plot of the data in Y versus the corresponding
values in X.
t (s) v (m/s)
– Example: Plot t vs. v in MATLAB using the plot function. 0 0
2 18.7292
>> v = [018.7292 33.1118 42.0762 46.9575 49.4214 50.6175 51.1871 51.456 … 4 33.1118
51.5823 51.6416]; 60 6 42.0762

>> t = [0:2:20]' 50
8 46.9575
10 49.4214
40

>> plot(t,v) 30
12 50.6175
14 51.1871
20
16 51.4560
10 18 51.5823
20 51.6416
0
0 2 4 6 8 10 12 14 16 18 20
DR. MOHAMAD A. ALKHALIDI 32
5 - Graphs & Plots in MATLAB
› Customizing the plot:
– title: Add title to the plot
› Syntax:
– title(‘add text’)
– title(title text, subtitle text): adds a subtitle underneath the title.
– title(___, Name, Value) modifies the title appearance using one or more name-
value pair arguments. For example, 'FontSize',12 sets the font size to 12 points.
Specify name-value pair arguments after all other input arguments. Modifying
the title appearance is not supported for all types of charts.

› Axis labeling: add labels to the axises


– xlabel(‘add x label’)
– xlabel(‘add y label’)

DR. MOHAMAD A. ALKHALIDI 33


5 - Graphs & Plots in MATLAB
› Customizing the plot: Marker Description
'o' Circle
– If you want to plot each '+' Plus sign
point with a specific line '*' Asterisk
Color Description
style, marker, and color '.' Point y yellow
include a specifier enclosed 'x' Cross m magenta
in single quotes in the plot '_' Horizontal line c cyan

function:
'|' Vertical line r red
Line Style Description 's' Square g green
- Solid line 'd' Diamond b blue
-- Dashed line '^' Upward-pointing triangle w white
: Dotted line 'v' Downward-pointing triangle k black
-. Dash-dot line '>' Right-pointing triangle
'<' Left-pointing triangle
'p' Pentagram
'h' Hexagram

DR. MOHAMAD A. ALKHALIDI 34


5 - Graphs & Plots in MATLAB

>>plot(t, v, 'o') >>plot(t, v, 's--g')


60 60

50 50

40 40

30 30

20 20

10 10

0 0
0 2 4 6 8 10 12 14 16 18 20 0 2 4 6 8 10 12 14 16 18 20

DR. MOHAMAD A. ALKHALIDI 35


5 - Graphs & Plots in MATLAB
› Customizing the plot:
60

– The default line width is 1 point.


– For the markers, the default size is 50

6 point with blue edge color and


no face color.
40

– We can control the line width as 30

well as the marker's size and its


edge and face (i.e., interior)
20

colors: 10

› plot(t, v, '--dc','LineWidth’,2,
'MarkerSize',10,'MarkerEdgeColor','k',' 0
0 2 4 6 8 10 12 14 16 18 20

MarkerFaceColor','m')

DR. MOHAMAD A. ALKHALIDI 36


5 - Graphs & Plots in MATLAB
› Customizing the plot:
– MATLAB allows you to display more than one data set on the
same plot.
– By default, previous plots are erased every time the plot
command is implemented.
– The hold on command holds the current plot and all axis
properties so that additional graphing commands can be added
to the existing plot.
– The hold off command returns to the default mode.
>> plot(t, v)
>> hold on
>> plot(t, u, 'o')
>> hold off

DR. MOHAMAD A. ALKHALIDI 37


5 - Graphs & Plots in MATLAB
60

50

40

30

20

10

-10
0 2 4 6 8 10 12 14 16 18 20

DR. MOHAMAD A. ALKHALIDI 38


5 - Graphs & Plots in MATLAB
› Customizing the plot:
– In addition to hold, another handy function is subplot, which
allows you to split the graph window into sub windows or
panes.
› It has the syntax:
>> subplot(m, n, p)
› This command breaks the graph window into an m-by-n matrix of small
axes and selects the p-th axes for the current plot.
– The plot3 command which has syntax: plot3
› It plot lines and points in 3-D space.
› plot3() is a three-dimensional analogue of plot().
>> plot3(x, y, z)

DR. MOHAMAD A. ALKHALIDI 39


5 - Graphs & Plots in MATLAB
› Customizing the plot:
– In plot3, x, y, and z are three vectors of the same length.
– The result is a line in three-dimensional space through the points
whose coordinates are the elements of x, y, and z.

– Example: Plotting a helix provides a nice example to illustrate its utility.


First, let's graph a circle with the two-dimensional plot function using
the parametric representation: x = sin(t) and y = cos(t).
– We employ the subplot command so we can subsequently add the
three-dimensional plot.
› >> t = 0:pi/50:10*pi;
› >> subplot(1,2,1);plot(sin(t),cos(t))
› >> axis square
› >> title('(a)’)
– Note that the circle would have been distorted if we had not used the axis square
command.

DR. MOHAMAD A. ALKHALIDI 40


5 - Graphs & Plots in MATLAB
› Customizing the plot:
› Now, let's add the helix to the
graph's right pane. To do this,
we again employ a parametric
representation: x = sin(t), y =
cos(t), and z = t
– >> subplot(1,2,2);
– >> plot3(sin(t),cos(t),t);
– >> title('(b)')

DR. MOHAMAD A. ALKHALIDI 41


5 - Graphs & Plots in MATLAB
› Customizing the plot:
– axis function is used to assign the minimums and maximums of the
axes:
› The first two values are the minimum and maximum for the x-axis, and
› the last two are the minimum and maximum for the y-axis.
– >> axis([xmin xmax ymin ymax])
– Other functions that are useful in customizing plots are clf, figure, and
legend:
› clf clears the Figure Window by removing everything from it.
› figure creates a new, empty Figure Window when called without any
arguments.
– Calling it as figure(n) where n is an integer is a way of creating and maintaining
multiple Figure Windows, and of referring to each individually.
› legend displays strings passed to it in a legend box in the Figure Window, in
order of the plots in the Figure Window.

DR. MOHAMAD A. ALKHALIDI 42

You might also like