0% found this document useful (0 votes)
77 views111 pages

Lectures 16 17 18 Linear Systems and MATLAB 2016 Handouts

Linear systems are problems that can be approximated by linear relationships. They are easy to solve using methods from linear algebra like matrices and vectors. A linear system of equations can be represented in matrix form as Ax=b where A is the coefficient matrix, x is the vector of unknowns, and b is the vector of known terms. The solution involves calculating the inverse of the A matrix and multiplying both sides by A-1 to solve for x.

Uploaded by

Stephen Alao
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)
77 views111 pages

Lectures 16 17 18 Linear Systems and MATLAB 2016 Handouts

Linear systems are problems that can be approximated by linear relationships. They are easy to solve using methods from linear algebra like matrices and vectors. A linear system of equations can be represented in matrix form as Ax=b where A is the coefficient matrix, x is the vector of unknowns, and b is the vector of known terms. The solution involves calculating the inverse of the A matrix and multiplying both sides by A-1 to solve for x.

Uploaded by

Stephen Alao
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/ 111

ECOR 1010

Lectures 16, 17 and 18


Linear Systems & MATLAB
Linear Systems
• Many problems in engineering can be
approximated by linear relationships
• For linear systems, solutions to problems are
often easy
– Methods for structured data representation,
management, and analysis
– Clear, logical, algebraic methods exist for solving
related engineering problems
• We will need tools from linear algebra
Taylor Series
The Taylor series of a function ƒ ( x ) that is
infinitely differentiable in the region of a
number 'a ' is the power series:
f ′( a ) f ′′( a ) f (3) ( a )
f ( x=
) f (a ) + ( x − a) + ( x − a) +
2
( x − a )3 + 
1! 2! 3!

= ∑n
b (
n =0
x − a ) n
When a is zero:
f ( x ) → b0 + b1 x + b2 x 2 + …
This slide is added to give some justification for the linear approximation. Generally,
functions can be expanded in a Taylor Series. If you know the value of a function at some
point a, you can calculate the value as some different point, x, away from a, with the Taylor
expansion. If x is not too far away, then x-a is small (i.e., much less than one), and therefore
higher powers of x-a are progressively smaller and smaller. A linear system is one where the
higher powers of x-a are so small that they can be ignored in the analysis. (Another point: at
the same time, the higher derivatives must also get ‘smaller’ so that the series converges).
The Taylor expansion is used to justify fitting to polynomials, such as power series in x.
Linear systems are ones where we can truncate the series after the linear term.
Example Linear Model
(mechanical system)

f = − kx
• Displacement of a
spring when a force is
applied (a linear
relationship for ‘small’
displacements)
Linear Equation
• Linear equation in variables xi

• The parameters ai and b are usually constants


• Can you give an example of a nonlinear
system/relationship?
Linear System of Equations
• A linear system can be described with a set of m
linear equations in the independent variables xi
Vector and Matrix
Representation
• We can represent linear systems in vector and
matrix form

A x = b
Vector and Matrix
Representation
5 x1 − x2 + x 3 =7
−2 x1 + 6 x2 + 9 x3 =0
−7 x1 + 5 x2 − 3 x3 =
−7

5 −1 1   x1   7 
 −2 6 9   x2  = 0
    
 −7 5 −3  x3   −7 

A x = b
3x3 3x1 3x1

Inner dimensions must be equal. Dimension of result, b, is the outer dimensions


Matrix Form
Rows

Columns
Vector and Matrix Operations
• Asian mathematicians had
already developed
algorithms for solving
linear systems by 250 BC
• Linear algebra as we
know it was first
formalized by German
mathematician Hermann
Grassmann(1809-77)
– This new algebra was
presented in his book Die
Ausdehnungslehre(1844)
– Grassmann algebra
Linear Algebra
• Deals with systems of linear equations and their
solutions, and
• linear transformations and their properties.
Solutions to Linear Systems
Solving a set of a linear equations means we determine
values for the n variables, x1, x2, ..., xn, such that each
of the m equations is satisfied.
 There are three possibilities:
• The system has a single unique solution.
– e.g. Two lines meet at a point, if they are not parallel
• The system has infinitely many solutions.
– e.g. Two planes meet in a line, if the planes are not parallel
• The system has no solution.
– e.g. Two planes, or two lines, never meet if they are parallel
Solutions to Linear Systems
Under-determined (m<n) Over-determined (m>n)
• Fewer equations than • More equations than
unknowns unknowns
• If a finite solution exists, it • A finite solution may exist
is not unique – It may, or may not, be unique
• If a solution exists there are
an infinite number of
solutions

 The equations must be independent. This means that if you


have two equations, you cannot simply add them to get a third
equation. You cannot simply multiply both sides of one
equation by some number, say 6, to get another equation.
Each equation must have new information, it cannot be a linear
combination of other equations.
Determined System (m = n)
• The number of equations equals the number of
unknowns
• If the equations are independent, then we can
solve for the unknowns.
– Unless the equations are inconsistent, like
x1=
+ x2 1 and x1= + x2 2
– Both of the equations cannot be true simultaneously

• Consider first systems with m = n = 2


Recall: Two equations – Two unknowns
• Solve for x1 and x2 : 3 x1 − 2 x2 =
5
5 x1 + 7 x2 =
4
• Multiply the top equ
15 x1 − 10 x2 = 25
by 5, and the bottom
equ by 3: 15 x1 + 21x2 = 12
• Subtract the bottom
from the top: 0 x1 − 31 x2 =13
• Solve for x2 x2 = −13 / 31 = −0.4191
• Sub x2 into either x=
1 (5 − 2 ×13 / 31) / 3
starting equ to get x1: = 1.3871
4

2
3 x1 − 2 x2 =
5
5 x1 + 7 x2 =
4
x2
x2

-2

Solution:
-4

-4 -2 0 2 4
x1 = 1.3871
x2 = −0.4194
x1
x1
With Matrices: 3 x1 − 2 x2 =
5
 Starting equations:
5 x1 + 7 x2 =
4
3 −2   x1  5 
 Write as Matrix, A, times a 5 7   x  =  4 
  2  
vector, x, equal to a vector b:
Ax=b
 Matrix multiply on the left -1 -1
by the inverse of A: A Ax=A b
1 0  -1
-1
A A=   = Unit Matrix x=A b
0 1 
• The trick is to calculate A-1: the matrix
that is the inverse of the A matrix.
Aside: 3 −2 
if A =  
 5 7 
• Do this calculation:  0.2258 0.0645
• Later, once you then A = 
-1

know MATLAB,  −0.1613 0.0968
calculate A-1.
1 0 
Show A A = 
-1

 0 1 

 x1   0.2258 0.0645 5   1.3871


=
-1
x  =A b
−   4   −0.4194 
 2  0.1613 0.0968    
In 3-Dimensions
• One linear equation (in three unknowns)
describes a plane in x-space
5 x1 − x2 + x3 =
7
• Three equations gives us three planes
Three Planes Intersecting at a Point

5 x1 − x2 + x 3 =7 80

−2 x1 + 6 x2 + 9 x3 =
60

0 40

x3 data (z)
20

−7 x1 + 5 x2 − 3 x3 =
−7 0

-20 15
10
5
-40 0

(x)
-5

x1 data
-60 -10
10 5 -15
0 -5 -10 -15
x2 data (y)
Example: System of Linear Equations
5 x1 − x2 + x 3 =7
−2 x1 + 6 x2 + 9 x3 =0
−7 x1 + 5 x2 − 3 x3 =
−7

 5 −1 1   x1   7 
 −2 6 9   x  = 0
  2  
 −7 5 −3  x3   −7 

A x = b
Typical Engineering Application
-1
• Find that satisfies x=A b
Three Planes Intersecting at a Point

80  x1   1.5701
 x  =  0.7196 
60
 2  
40  x3   −0.1308
x3 data (z)

20

0 •This is the intersection point of


the three planes.
-20 15
10

-40
5
0
•Show this yourself later using
(x)

-5 MATLAB and Maple


x1 data

-60 -10
10 5 -15
0 -5 -10 -15
x2 data (y)
Mesh Current Network Analysis

i1 i2 i3

• Kirchhoff’s voltage law: the sum of the voltage


drops around any closed loop is equal to the
sum of the voltage rises. (Recall Ohm's Law: V = i R)
Loop 1: i1 (6 + 5) − i2 5 + i3 × 0 =50
Loop 2: -i1 (5) + i2 (5 + 18 + 4) − i3 × 4 =0
Loop 3: i1 (0) − i2 4 + i3 (4 + 4) =
0
Mesh Current Network Analysis

i1 i2 i3

• Kirchhoff’s voltage law: the sum of the voltage


drops around any closed loop is equal to the
sum of the voltage rises.
 11 −5 0  i1  50 
 −5 27 −4  i  = 0
  2  
 0 −4 8  i3   0 
A x = b
First, solve the slow way by hand ...
 11 −5 0  i1  50 
 −5 27 −4  i  = 0
  2  
 0 −4 8  i3   0 

11 −5 0 50
−5 27 −4 0
0 −4 8 0
Row Reduction to Row Echelon Form
11 −5 0 50
• The system of equations
−5 27 −4 0
is written in this form: 0 −4 8 0

• This form is then modified using 1 0 0 5


elementary row operations until it 0 1 0 1
reaches reduced “row echelon form”: 0 0 1 0.5
• There are three types of elementary
row operations:
– Type 1: Swap the positions of two rows.
– Type 2: Multiply a row by a nonzero scalar.
– Type 3: Add to one row a scalar multiple of another.
11 −5 0 50 Take 4/25ths of the second row
MATLAB code:
−5 27 −4 0 and add it to the third row
0 −4 8 0 10 0 0 50 >> A=[11 -5 0;-5 27 -4;0 -4 8]
A=
Take 1/2 of the third row 0 25 0 25
11 -5 0
and add it to the second row 0 0 8 4 -5 27 -4
0 -4 8
11 −5 0 50 Divide the first row by 10,
>> b=[50;0;0]
−5 25 0 0 the second row by 25
b=
0 −4 8 0 and the third row by 8. 50
Take 1/5 of the second row 1 0 0 5 0
0
and add it to the first row 0 1 0 1 >> x=inv(A)*b
10 0 0 50 0 0 1 0.5 x=
−5 25 0 0 5.0000 Different
1.0000 ways of
0 −4 8 0
1 0 0  i1   5  0.5000
>> x=A\b
getting the
 0 1 0  i  =  1 
Take 1/2 of the first row answer
x=
and add it to the second row   2   5.0000
-------
10 0 0 50 0 0 1  i3  0.5 1.0000 A\b is
0 25 0 25 0.5000 faster
0 −4 8 0

Unit Matrix in 3D
Another Linear Circuit Example

15 −5 0 −5 −1 i1   40 


 
 −5
 15 −5 0 −2  i2   −40 
0 −5 15 −5 −3 i3  =  40 
    
 −5 0 −5 15 −4  i4   −50 
 −1 −2 −3 −4 10  i5   0 

Difficult to solve by hand!!


This MATLAB m-file
example is called:
circuit.m
This is the script file. It is
the computer program.
To run the script:
•Click the run icon in the
editor
or
•Type ‘circuit’ in the
command window

Click on the yellow icon by A and the


window in the next slide pops up
This spreadsheet can be edited
Example from Mechanics
Three Equations, Three
Unknowns
Linear System of Equations

 − sin10 − sin 30 sin10   FA   0 


 cos10 cos 30 cos10   FB  =  850 
    
 cos10 0 −2 cos 10  FC   −425
Example: Trusses
Example: Trusses
• For each joint, the sum
of the forces in each
direction (x and y) must
be zero (static)
In Matrix Form
5 4√2
4
3 4
Another Truss
Example
Solve this by hand?
Solving Systems of Linear Equations
• We can solve these linear equations either by
hand, or with software
– MATLAB and Maple in this course (… and Excel)
• MATLAB is good for numerical calculations
and solving systems with unique solutions
• Maple can be useful for finding algebraic
solutions when the solution is not unique
What is MATLAB?
• MATrixLABoratory (MATLAB)
• Designed for matrix computations
• Used extensively in mathematics, engineering,
and computer science
• Usually used for numerical purposes
• Has some symbolic capabilities (but Maple is
better for symbolic manipulations)
• Handles large data sets quite well
What can MATLAB do?
• Basic mathematics
• Matrix manipulation
• 2D graphing
• 3D graphing
• Surface plotting
• Sound Visualization
• Data Analysis
• Computer Programming
• Much more
– There are many specialized “toolboxes”
Three Basic Windows
• Editor Window
– Used primarily for programming,
and developing reusable code

• Command Window
– Opens immediately when you start
MATLAB
– Used primarily for mathematical
operations, testing/development,
and for creating throw away
programs

• Figure Window
– Appears whenever a plot is
created
Video Time
1. http://www.mathworks.com/demos/matlab/getting-
started-with-matlab-video-tutorial.html
2. http://www.mathworks.com/demos/matlab/working-
in-the-development-environment-matlab-video-
tutorial.html
3. http://www.mathworks.com/demos/matlab/writing-
a-matlab-program-matlab-video-tutorial.html
4. http://www.mathworks.com/demos/matlab/analyzin
g-data-overview-matlab-video-demonstration.html
Semicolons ;
• Follow commands when you do not want the
output to be printed/echoed to the screen
• Can be used in the command window or in
your m-files (so you see only what you want)
» 1+1
ans =
2
» 2*18;
»
Variables
• You do not need to initialize variables (i.e., no
need to assign data types)
– MATLAB does it automatically
• Can have different types
– Double Precision (default)
– Integers
– Boolean
– Strings
• Can be multidimensional (vectors, matrices)
Variables
• Use the = sign to define variables
Number1 = 412;
% Value 412 is assigned to the variable Number1
Number_1 = -18;
% Note that Number1 and Number_1 are different
Number 2 = 15;% Invalid -> Names cannot have spaces
A1 = [1 2 3; 4 5 6; 7 8 9];% Assigns a matrix A1
AVector = [-1; 0; 1; 0; -1; 0];
2V = [34; 52]; % Invalid: Names must begin with a letter
Displaying Variables in Scripts

disp(Number)
% Will display the contents of the variable Number
in the command window
disp('At dawn, my father and I picked carrots off
of the trees')
% Display the message in between quotations in the
command window
% If you want an apostrophe in the message, you
have to use 2 single quotes: ''
Parentheses
( ) used to denote order of operations or standard
functions
2*(3 + 4) or sin(3.145)

( ) used to denote elements of


a matrix/vector
A(1,2)=2

( ) used to enclose arguments of functions:


cos(x), exp(x), log(x), disp(Number)
MATLAB Workspace
• When you create a variable it is stored in the
MATLAB workspace
– You can access it in later calculations
• If you want to clear the workspace
– clear all; % clears all variables
– clear A1; % clears variable A1
Cleaning Up
• You can clear the command window with the
command clc
• You can close all open figure windows with
the command close all
Vector Operations in MATLAB
• Use square brackets for vectors and matrices: [ ]
• For row vectors, use a space or comma between
elements
a = [1,2,3] or a = [1 2 3]

• For a column vector, use a semicolon (;) between


elements
a = [1;2;3]
Assigning Matrices
1 2 
A = [1, 2; 3, 4] A= 
3 4 
1 3 
Matrix transpose A’ A' =  
 2 4 
Addition and Subtraction

>> A = [5;1;3;4];
>> B = [0;2;4;11];
>> C = A-B

C=

5
-1
-1
-7
Scalar-Vector Operations
>> a = [-1,-5,0,3,7,8];
>> 3*a

ans =

-3 -15 0 9 21 24

>> 1 + a

ans =

0 -4 1 4 8 9
Norm of a Vector
>> a = [-1;-5;0;3;7;8]
• Use the norm a=
command
-1
-5
0
norm of vector a ≡ a 3
7
8

= a + a + a …+ a
2
1
2
2
2
3
2
n >>norm(a)

ans =

12.1655
Cross Product
>> J = [2;1;-3];
>> K = [0;-2;4];
>>cross(J,K)

ans =

-2
-8
-4

>>cross(K,J)
Moment of a force Fb applied at point 'b' ans =
  
around point 'a' is given as : M=a rab × Fb .

 
2
 8
a × b =a b sin θ n 4

 
Force on a moving charged particle in a magnetic field is: F=
B qv × B
Dot Product (Inner Product)
• The dot product of two vectors is a scalar
• The vectors must have exactly the same
number of elements

• For vectors in 2D and 3D


 F
x·y = x y cos θ θ


e.g. Mechanical Work, =
W F=
·d F d cos θ
Dot Product Example
Check the following dot product result

x ⋅ y= (7)(−1) + (4)(5) + (1)(9) MATLAB m-file code in


= 22 the top “Editor” window

The next slide The Command Window


has a magnified shows the results of
view of the code. running the m-file
Calculate the Cosine
of the Angle
between the
vectors x and y

x⋅y
cos(θ ) =
x y

The next slide


has a magnified
view of the code.
The Dot Product and the Correlation Coefficient

x⋅y x1 y1 + x2 y2 +… xn yn
cos(θ )
= =
x y x + x …+ x
2
1
2
2
2
n y + y …+ y
2
1
2
2
2
n

∑ ( xi − x )( yi − y ) 1 n
rxy = i =1 =sx ∑
n − 1 i =1
( xi − x ) 2

(n − 1) sx s y
n
1
=sy ∑
n − 1 i =1
( yi − y ) 2
10
r2 = (-0.9934)2=0.9868
Coefficient of
8
Determination
6
of the fit:
r2 = 0.9868

Y Data
4

-2
0 1 2 3 4 5 6 7 8

X Data

Coefficient of
4
Determination
2
of the fit:
r2 = 0.9868

Y -mean(y)
0

-2

-4

-6
-4 -3 -2 -1 0 1 2 3 4

X -mean(x)
7   3
x − mean( x)=  4  − 4=  0 θ = 173 o
 
1  -3
6

te
0.8
-1 -5.333

ordina
y − mean( y ) = 5  − 4.333 =0.667 
2 0.6

Co
0.4

d
0
 9   4.667 

ordinate
T hi
0.2
-2
0.0

Second Co
-4
-4 -2 0 2 4
First Coordin
ate

cos θ =−0.9934 ⇒ θ =173 °

The angle between these two vectors is 173o


Correlation Coefficient and the Dot Product

• The correlation coefficient is the cosine of the


‘angle’ between the vectors:
x-mean(x) and y-mean(y).

r=1

r=0

r = -1
Recall the Car
Mileage example
Weight
Mileage
Fuel Consumption versus Car Weight
40

35

30
City Mileage (mpg)

25

20

15

10

5
10 20 30 40 50 60

Car Weight (x 100 lbf)

yˆ =
−(0.8 ± 0.1) x + (48 ± 3) [mpg]
r2 0.89 ⇐ (-0.9425) 2
40 15

City Mileage - Average City Mileage (mpg)


35 10

30 5
City Mileage (mpg)

25 0

20 -5

15 -10

10 -15

5 -20
10 20 30 40 50 60 -15 -10 -5 0 5 10 15 20 25
Car Weight (x 100 lbf) Car Weight - Average Car Weight (x 100 lbf)
Matrix Operations in MATLAB
Full-Colon Operator
• Use a full colon to pick out rows or columns
>> A(:,2)
>> A = [1, 2, 3; 4, 5, 7; 8, 9, 10]
ans =
A=
2
1 2 3 5
4 5 7 9
8 9 10
>> A(3,:)

ans =

8 9 10
Full-Colon Operator
Full-Colon Operator
• Easily create arrays with a fixed step size
>> [1:2:10]

ans =

1 3 5 7 9

>> [0:0.5:2.5]

ans =

0 0.5000 1.0000 1.5000 2.0000 2.5000


Operations on Matrices
• Addition and subtraction
>> A + B
• Multiplication
>> A*B
• Inversion
>>inv(A)
• Powers (works for what kind of matrices?)
>> A^4
Special Matrices
• Identity matrix
>> eye(4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Special Matrices
• Zeros (a matrix of all zeros)
>> zeros(3,2)
ans =
0 0
0 0
0 0
• Ones (a matrix of all ones)
>> ones(4,19)
Element-Wise Operations on Matrices
• You can perform element-wise operations
rather than standard matrix operations
Matrices must have the same dimension
• Multiply element-by-element
>> A.*B
• Raise each element of the matrix to a Power
>> A.^4
• Divide element-by-element
>> A./B
Programming in MATLAB
• Powerful, yet simple programming language
– Very little syntax
• Many built-in functions
– Saves you having to code your own
– Can be slow, in some cases …
• Able to do matrix manipulations
• Can develop two types of m-files (programs)
– Scripts for running a sequence of commands
– Functions for creating new tools (functions)
Script m-Files
• A sequence of commands
– For example, as you would type them at a prompt
• Cannot accept arguments
– Functions can have arguments
• Uses the MATLAB Workspace as its working
environment
– Global variables
• We have seen examples already
Function m-Files
• Creates a new MATLAB function
• Can accept arguments (inputs) and return
outputs
• Uses local variables that do not appear in the
MATLAB Workspace
• We will look at function files later
For Loops
• Repeat a set of
commands a
specified number
of times:
for variable = expression
statements
end
Taylor Expansion for ex
2 3 4
x x x x
e =+
x
1 + + + +…
1! 2! 3! 4!

1 1 1 1
e =1 + + + + +…
1

1! 2! 3! 4!
x x 2 x3 x 4
e =+
x
1 + + + +…
1! 2! 3! 4!

1 1 1 1
e1 =1 + + + + +…
1! 2! 3! 4!
Nested Loops

• You can also create


nested loops
Relational and Logical Operators

< Less than


<= Less than or equal to
> Greater than
Relational
>= Greater than or equal to Operators
== Equal to
~= Not equal to

~ Not Boolean
& And Logical
| Or
Operators
Relational and Logical Operators
• Used when comparing and selecting values
• Used to determine if an expression will
evaluate to true or false
• Used in if statements and while loops
• Used whenever a logical decision must be
made
If Statements
• Executes the if (expression)
statements if the
expression is true statements
– Use the relational or
logical operators
end
• Otherwise, skips the
statements
• Statements can be any
code or function
– Can have multiple
statements
Notice how you
need to double
apostrophes (‘’)

In the second example, when you type 11 for Your_Age,


the program simply ends with no output.
If-Else Statements
• One of the two statements is always executed

if (expression)
statements
else
statements
end
Always Include Error Messages!
Formatted Printing: In a string of text written within single quotation marks:
% followed immediately with a formatting code means place the corresponding
value listed at the end of the command in this location in the string using the
specified format.
Format for output: ‘i’ for integer; ‘5.2f’ for floating point number of five characters with 2
digits to the right of the decimal point.
(\r means carriage return, and is the same as \n which means new line)
Elseif (and MATLAB Help)
You could write the
program on the previous
slide with ‘else’ and ‘if’
statements instead of
‘elseif’, but you would
need another ‘end’
statement
While Loops
• Repeat a set of
commands while a while expression
condition holds true (1) statements
– Tests the condition before
action is taken end
• Exits when the condition
is found false (0)
• Used when you do not know how many times
you will loop
• While loops carry an implicit danger: there is no
guarantee, in general, that you will exit a while
loop.
While Loops
a = 2; • Loop while the square
b = a^2; of a number is less than
a value of 2000
while b< 2000
• Find the largest even
a = a + 2;
integer with a square
b = a^2; less than 2000
end
a = a - 2;
disp(a)
Changed to
largest odd
integer whose
square is less
than 2000.
The example codes so far were all
written as script m-files
• Now we will look at function files
• In this case we create out own functions:
– for instance, the computer has built-in
functions like sin(x), cos(x), tan(x), log(x),
which take an input, x, and return a value
depending on what the function does.
• Our functions will be similar. They will
have input(s), do something with the
input(s), and output some value(s).
Function m-Files
• Syntax is given by:
function [out1, out2, ...]
=funname(input1, input2, ...)
• The function name must be the same as the
file name (funname.m)
– The m-file begins with the function declaration
• Output arguments are specified in square
brackets
• Use the function from the command prompt
or in a script file, just like any other MATLAB
function
Notice the use of the
dot in the formula

Notice that there is no


clear command on the first
line, as there was in the
previous script files. This
is because all variables
inside functions are local
to that function. It doesn’t
matter what symbols you
use inside a function; for
instance, they can be the
same symbols you used in
the program that called the
function.
• On the next slide is a function that has a
vector output: stats.m
• You read a vector in of any length, called
‘data’ in this example
• The function returns a 1x3 vector with the
mean, standard deviation, and the number
of data points in the vector called ‘data’.
Things to Remember when Writing
Computer Programs
• Use the indented style that you have seen in the
previous programs. It makes the programs easier to
read, the syntax is easier to check, and it forces you to
think in terms of building your programs in blocks.
• Put lots of comments in your program to tell the reader in
plain English what is going on. Some day that reader will
be you, and you will wonder what you did.
• Put error messages in your programs, like the test for
when the denominator was zero. As you go through your
career, your programs will build on each other. Error
messages will help you debug future programs.
• If you are having trouble writing a program, get a small
part of it running and try to build on that.
MATLAB Plotting Tools
• MATLAB has very extensive plotting
(graphing) tools, for many types of
information
• Basic command is plot
– plot(x,y) plots a y versus x graph
– You can plot multiple data sets on one graph
• plot(x1,y1,’b’,x2,y2,’r’)
• One in blue (b), one in red (r)
Plotting Example
>>x = [1;2;3;4;5;6;7;8;9;10];
>>y = [10;7;5;4;3.5;3;2.75;2.5;2.25;2];
>>plot(x,y)
>>xlabel('x')
>>ylabel('y')
>>title('An Example Plot for ECOR 1010')
Another Plotting Example
>>x = [1;2;3;4;5;6;7;8;9;10];
>> y1 = [2;4;9;6;7;6;5;4;3;2];
>> y2 = [3;7;10;5;3;6;5;1;0;0];
>> plot(x,y1,'b',x,y2,'g--')
>>xlabel('x')
>>ylabel('y')
MATLAB for Simulation
• MATLAB is a powerful tool for creating
simulations of physical systems
– Can be used to efficiently solve differential
equations (e.g., equations of motion)
– Simulations can be used to check anticipated
results before building real systems
• Simulink is a powerful graphical tool in
MATLAB for creating simulations
Simulation Example (MobotSim)
• Simulate the motion of
a mobile robot
• Simulate the sensors on
a mobile robot
– Wheel rotations
– Laser rangefinder
readings
• Save the data to test
algorithms without
needing a real robot

You might also like