0% found this document useful (0 votes)
17 views41 pages

ENGR 1204 Lecture 5

The document covers the concepts of solving systems of linear algebraic equations using matrix representation and MATLAB functions. It explains how to represent equations in matrix form, compute the matrix inverse, and solve equations using MATLAB commands. Additionally, it provides examples of plotting data points and creating various types of plots in MATLAB.

Uploaded by

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

ENGR 1204 Lecture 5

The document covers the concepts of solving systems of linear algebraic equations using matrix representation and MATLAB functions. It explains how to represent equations in matrix form, compute the matrix inverse, and solve equations using MATLAB commands. Additionally, it provides examples of plotting data points and creating various types of plots in MATLAB.

Uploaded by

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

ENGR 1204 Programming

Languages in Engineering
Matrix Solutions to Systems of Linear Algebraic
Equations
Plotting Week 5

Attaway MATLAB 6E – Chapters 14, 3,


and 12
Linear Algebraic Equations
A system S of linear algebraic equations is a
set of equations of the form:
a11x1 + a12x2 + a13x3 + …. + a1nxn = b1
a21x1 + a22x2 + a23x3 + …. + a2nxn = b2
a31x1 + a32x2 + a33x3 + …. + a3nxn = b3
... ... ...
am1x1 + am2x2 + am3x3 + …. + amnxn = bm

This is called an m×n system of equations;


there are m equations and n unknowns.
2
Matrix Representation
This system of equations can be rewritten in matrix
form as
Ax = b (Note: this uses matrix multiplication)
where A is a matrix of the coefficients, x is a column
vector of the unknowns, and b is a column vector of
the constants from the right-hand side of the
 a11 a12 a13  a1n   x1 
equations:  b1 
a a 22 a 23  a 2 n   x 2  b 
 21  2
 a31 a32 a33  a3n   x3  =  b3 
     
          
 a m1 am2 a m3  a mn   x n   bm 
3
Solving the Matrix Form
All systems of linear equations have either:
no solutions (linearly dependent rows)
one solution
infinitely many solutions (identical rows)

To solve for x:


x = A-1 b
So, if we can find the matrix inverse A -1 , we
can solve! 4
Matrix Inverse
If the result of multiplying a matrix A by a
matrix B is the identity matrix, then B is the
inverse of matrix A
The inverse of a matrix A is written as A -1
So, [A][A-1] = [I]
How to actually compute the inverse A -1 of a
matrix by hand is not so easy

5
Matrix Inverse Hand Calculation:
2 x 2 Systems
a a12 
For a 2 x 2 matrix A =  11  ,
 a 21 a 22 

the matrix inverse is defined as

1  a 22  a12 
A-1 =
D   a 21 a11 

where the D is called the determinant and is defined as:

a11 a12
D = = a11 a22 – a12 a21
a 21 a 22

6
MATLAB Functions
Related functions in MATLAB:
matrix inverse: inv
determinant: det

To solve systems of equations in MATLAB


x = inv(A)*b
x = A\b

7
Determinant of a Matrix – Singularity
A singular matrix is a matrix whose
determinant is zero
A matrix is singular when
Two or more rows of a given matrix are
identical
Elements of two or more rows of a matrix are
linearly dependent
It is NOT possible to find the inverse of a
matrix if it is singular

8
Singular Matrix: Example 1
 2 1 4
 
Consider matrix [A] with  A  2 1 4
two identical rows:  1 3 5

2 1 4
det A  2 1 4
1 3 5
2 15 14 1 4 23 125 2 43 411
10  4  24  10  24  4 0

9
Singular Matrix: Example 2
Consider matrix [A] with 2 1 4
the elements of its first and  A 14 7 28
second row being linearly  1 3 5 
dependent :

2 1 4
det A 14 7 28
1 3 5
2 7 5 1281 4 14 3 114 5 2 283 4 7 1
70  28  168  70  168  28 0

10
Example of Solving System of Linear
Algebraic Equations Using MATLAB
Given: the following system of equations:

2 x1  x2  x3 13
3 x1  2 x2  4 x3 32
5 x1  x2  3 x3 17
Find: values of x1, x2, and x3
Solution:
coefficient matrix [A] and right-hand side matrix [b] are

[A]b

11
Example of Solving System of Linear
Algebraic Equations Using MATLAB (cont’d)
>> A = [2 1 1; 3 2 4; 5 -1 3]
A =
2 1 1
3 2 4
5 -1 3
>> b = [13 32 17]'
b =
13
32
17
>> x = inv(A)*b
x =
2.0000
5.0000
4.0000
>> x = A\b
x =
2.0000
5.0000
4.0000

12
Simple Plots
 Simple plots of data points can be created using plot
 To start, create variables to store the data (can store one or
more point but must be the same length); vectors named x
and y would be common – or, if x is to be 1,2,3,etc. it can be
omitted
plot(x,y) or just plot(y)
 The default is that the individual points are plotted with
straight line segments between them, but other options can
be specified in an additional argument which is a character
vector
 options can include color (e.g. ‘b’ for blue, ‘g’ for green, ‘k’
for black, ‘r’ for red, etc.)
 can include plot symbols or markers (e.g. ‘o’ for circle,
‘+’, ‘*’)
 can also include line types (e.g. ‘--’ for dashed)
 For example, plot(x,y, ‘g*--’) 13
Labeling the Plot
By default, there are no labels on the axes or title on
the plot
Pass the desired character vectors or strings to these
functions:
 xlabel(‘string’)
 ylabel(‘string’)
 title(‘string’)
 subtitle(‘string’)
The axes are created by default by using the minimum
and maximum values in the x and y data vectors. To
specify different ranges for the axes, use the axis
function:
 axis([xmin xmax ymin ymax])
Calling the axis function without passing arguments
returns the bounds used for the x and y-axis ranges
The axis padded command puts space around the
14
Example: Plotting One Point
plotonepoint.m
% This is a really simple plot of just one point!

% Create coordinate variables and plot a red '*'


x = 11;
y = 48;
Time and Temp (Fahrenheit)
plot(x,y,'r*') 55

% Change the axes and label them


axis([9 12 35 55]) 50
xlabel('Time')
ylabel('Temperature')
% Put a title on the plot Temperature
45
title('Time and Temp (Fahrenheit)')

40

35
9 9.5 10 10.5 11 11.5 12
Time

15
Example: Plotting Multiple Points
timeandtemps.m
% Create coordinate vector variables
x = 8:11; Time and Temperatures

y = [31 37 46 48]; (Fahrenheit)

48

% Plot points and add labels 46

figure 44

42
plot(x,y,’b*')

Temperature
40

title('Time and Temperatures') 38

subtitle('(Fahrenheit)') 36

34

xlabel('Time') 32

ylabel('Temperature') 30
8 8.5 9 9.5
Time
10 10.5 11

% Create some space around the points


axis padded

16
Other Plot Functions
clf clears the figure window
figure creates a new figure window (can #
e.g. figure(2))
hold is a toggle; keeps the current graph in
the figure window
legend displays strings in a legend
grid displays grid lines
bar bar chart
yline creates horizontal line(s)
xline creates vertical line(s)
Note: make sure to use enough points to get
a “smooth” graph
17
Example: Plotting Two Figures
plot2figs.m
% This creates 2 different plots, in 2 different
% Figure Windows, to demonstrate some plot features
clf
x = 1:5; % Not necessary
y = [2 11 6 9 3];
% Put a bar chart in Figure 1
figure(1)
bar(x,y)
% Plot the points and use yline in Figure 2
figure(2)
plot(x,y,'ko')
hold on
yline(5)
axis padded
grid on
18
Example: Plotting Two Figures (cont’d)
12
11

10 10

9
8
8

7
6
6

5
4
4

2 3

2
0
1 2 3 4 5 1 1.5 2 2.5 3 3.5 4 4.5 5

19
Example: Plotting Two Curves on One
Graph
sinncos.m
% This script plots sin(x) and cos(x) in the same Figure Window
% for values of x ranging from 0 to 2*pi
clf
x = 0: 2*pi/40: 2*pi; sin and cos on one graph

sin
1
% y = sin(x); X 1.5708
cos

Y1
% plot(x,y)
% hold on 0.5 Data Tips Tool
% y = cos(x);
sin(x) or cos(x)
% plot(x,y)
0

plot(x,sin(x),x,cos(x))
-0.5
axis padded
legend('sin', 'cos')
-1
xlabel('x')
ylabel('sin(x) or cos(x)') 0 1 2 3 4 5 6
title('sin and cos on one graph') x

20
Subplot
The subplot function creates a matrix (or vector)
in a Figure Window so that multiple plots can be
viewed at once
If the matrix is m×n, the function call
subplot(m,n,i) refers to element i (which must
be an integer in the range from 1 to m*n)
The elements in the Figure Window are
numbered row-wise
It is sometimes possible to use a for loop to
iterate through the elements in the Figure
Window
21
Subplot Example
For example, if the subplot matrix is 2×2, it
may be possible to loop through the 4
elements to produce the 4 separate plots
Plot 1 Plot 2
Plot 3 Plot 4

for i = 1:4
subplot(2,2,i)
% create plot i
end

22
Log Plot Functions
The plot function uses linear scales for both
the x and y axes
Functions that use logarithmic scales for
axes:
loglog uses log scales for both x and y axes
semilogx uses a log scale for the x axis and
linear scale for the y axis
semilogy uses a linear scale for the x axis and
a log scale for the y axis

23
Log Plot Example
logplot.m 10
10 9 plot
10 10
semilogy

subplot(1,2,1) 9

plot(logspace(1,10)) 8 10 8
title('plot') 7
subplot(1,2,2)
6 10 6
semilogy(logspace(1,10))
title('semilogy') 5

4 10 4

2 10 2

0 10 0
0 20 40 60 0 20 40 60

24
More Plot Functions
Just like the plot function, the following
functions use x and y vectors of data values:
The bar function draws a bar chart
barh draws a horizontal bar chart
area draws the plot as a continuous curve and
fills in under the curve that is created
stem draws a stem plot
scatter is similar to plot, uses small circles for
the points

25
Subplot of scatter,bar,area,stem
4 Plot types
scatter bar
2
1.8
Population (mil)

Population (mil)
1.6 1.5

1.4
1
1.2
0.5
1
0
2018 2019 2020 2021 2022 2018 2019 2020 2021 2022
Year Year
area stem
2
Population (mil)

Population (mil) 1.5


1.5

1 1

0.5 0.5

0 0
2018 2019 2020 2021 2022 2018 2019 2020 2021 2022
Year Year

26
Subplot of scatter,bar,area,stem
subplottypes.m
(cont’d)
% Subplot to show plot types
year = 2018:2022;
pop = [0.9 1.4 1.7 1.3 1.8];
subplot(2,2,1)
scatter(year,pop)
title('scatter')
xlabel('Year')
ylabel('Population (mil)')
axis padded
subplot(2,2,2)
bar(year,pop)
title('bar')
xlabel('Year')
ylabel('Population (mil)')
subplot(2,2,3)
area(year,pop)
title('area')
xlabel('Year')
ylabel('Population (mil)')
subplot(2,2,4)
stem(year,pop)
title('stem')
xlabel('Year')
ylabel('Population (mil)')
axis padded
sgtitle('4 Plot types')
27
Bar, Stacked Bar for Matrices
Bar Stacked Bar
45 160

40 140

35
120

30
100
25

Ages
Ages

80
20
60
15

40
10

5 20

0 0
1 2 1 2
Group Group

>> groupages = [8 19 43 25; 35 44 30 45] >> bar(groupages,'stacked')


groupages = >> xlabel('Group')
8 19 43 25 >> ylabel('Ages')
35 44 30 45
>> bar(groupages)
>> xlabel('Group')
>> ylabel('Ages') 28
Histograms
Histograms show the frequency of
occurrence of values within a vector
 Bins are used to collect values in given ranges
 By default, histogram(vec) determines the number

of bins, or histogram(vec,n) specifies n bins


The resulting plot is a type of bar chart in
which the height of each bar is the number of
values that fall in that particular bin
In an assignment statement,
ch = histogram(vec)
would store the output handle in an object
variable so that the properties could then be
inspected or modified
29
Histogram Example
histexample.m Quiz Grades
4

quizzes = [10 8 5 10 10 ... 3.5

6 9 7 8 10 1 8]; 3

figure 2.5
H = histogram(quizzes)
2

#
xlabel('Grade')
1.5
ylabel('#')
title('Quiz Grades') 1

0.5

>> histexample 0
H = 0 1 2 3 4 5 6 7 8 9 10 11
Grade
Histogram with properties:

Data: [10 8 5 10 10 6 9 7 8 10 1 8]
Values: [1 0 0 0 1 1 1 3 1 4]
NumBins: 10
BinEdges: [0.5000 1.5000 2.5000 … ]
BinWidth: 1
BinLimits: [0.5000 10.5000]
Normalization: 'count'
FaceColor: 'auto'
EdgeColor: [0 0 0]
30
Pie charts
• The pie function creates a pie chart
>> pie([11 14 8 3 1])

3%
8%

30%

22%

38%

31
Pie charts (cont’d)
A string cell array as a second argument would
print the strings instead of percentages on the
pie pieces
>>pie([2 4 3 5],{'North','South','East','West'})
North

West

South

East

32
Animation
There are a couple of functions that will show
animated plots:
comet(x,y): the end result is like plot(x,y),
but it displays one point at a time
the function movie(M) displays recorded
movie frames
The frames are first captured in a loop using
the built-in function getframe, and are stored
in a matrix M.

33
Animation Example
>> x = 0:1/100:2*pi;
0.8
>> y = sin(x);
0.6
>> comet(x,y)
0.4

0.2

-0.2

-0.4

-0.6

-0.8

0 1 2 3 4 5 6

34
Customizing Plots
There are many ways to customize figures in
the Figure Window:
Clicking on the Plot Tools icon will bring up the
Property Editor and Plot Browser, with many
options for modifying the current plot
Additionally, there are properties that can be
modified from the default in the plot function
itself
Using the help facility with the function name
will show all of the options for that particular
plot function
35
Three Dimensional Plots
Many 2D plot functions have 3D equivalents,
e.g. plot3, bar3, bar3h, stem3, pie3, and
comet3
Once the plot is in the Figure Window,
clicking on the Rotate 3D icon allows you to
view the plot from different angles
Using the grid function makes it easier to see
the data points
Use zlabel to label the z axis

36
3D Plot Example
plot3D.m
t = 0:pi/50:10*pi;
plot3(exp(-0.05*t).*sin(t),...
exp(-0.05*t).*cos(t),t),...
xlabel('x'),ylabel('y'),zlabel('z')
grid
title('3D Plot')

37
mesh and surf functions
The mesh function draws a wireframe mesh of
3D points
The surf function creates a surface plot by using
color to display the parametric surfaces defined
by the points
Can use sphere function or the cylinder function
to generate matrices of the x,y, and z coordinates
to pass to mesh or surf
Can also use meshgrid to create the matrices of
x and y coordinates, and then calculate z as a
function of x and y
The colorbar function will show the range of
38
mesh Example
>> [x,y,z] = sphere(15);
>> size(x)
ans =
16 16
>> mesh(x,y,z)
>> title('Mesh of sphere')

39
surf Example
>> [x,y,z] = sphere(15);
>> surf(x,y,z)
>> title('Surf of sphere')
>> colorbar

40
meshgrid Example
>> [x,y] = meshgrid(-2*pi:0.1:2*pi);
>> z = cos(x)+sin(y);
>> surf(x,y,z)
>> title('cos(x)+sin(y)')
>> xlabel('x')
>> ylabel('y')
>> zlabel('z')

41

You might also like