u niversity of v aasa communications and systems engineering group tlte.3120 computer simulation in...
Post on 12-Jan-2016
216 Views
Preview:
TRANSCRIPT
UNIVERSITY of VAASA Communications and Systems Engineering Group
TLTE.3120 Computer Simulation in Communication and Systems (5 ECTS)
http://www.uva.fi/~timan/TLTE3120
Lecture 1 – 9.9.2015
Timo Mantere
Professor, Embedded systemsUniversity of Vaasa
http://www.uva.fi/~timantiman@uva.fi
1
UNIVERSITY of VAASA Communications and Systems Engineering Group
Lectures & Excercises
Lectures Wednesdays 14-17 in Technobotnia class TF4104
Week 38 Thursday 17.9. 8-11 … Ends week 44
Exercises Thursdays 15-18 TF4104
Week 38 Thursday 17.9. 13-16 … Ends week 45
Participating is not obligatory
Due duties in Seinäjoki some classes might have to be rescheduled
2
UNIVERSITY of VAASA Communications and Systems Engineering Group
Lecture 1
Information about Course arrangements & schedule What is Matlab What is Simulink What is Simulation Basics of modelling
3
UNIVERSITY of VAASA Communications and Systems Engineering Group
Course Website
Follow the page continuously – every piece of course material will be added there Lectures Exercises Homeworks Important announcements Course results (announcement is e-mailed over Oodi, when
results are available)
http://www.uva.fi/~timan/TLTE3120
4
UNIVERSITY of VAASA Communications and Systems Engineering Group
General
Credits: 5 ECTS Prerequisites: one can take this course without prior
knowledge of Matlab or Simulink
Passing the course Passing the mandatory exercises, homeworks and final exam
50% Final homework ( “Project”) 50% Final examination 0% Homeworks 0% Class exercises
Grading Usual 1-5 or failed Based on points collected from mandatory exercises,
homeworks and final exam
5
UNIVERSITY of VAASA Communications and Systems Engineering Group
Course Contents
Getting started with MATLAB and SIMULINK Writing simple programs with Matlab Design simple models with Simulink Matlab and Simulink toolboxes Matlab as a part of the simulation environment Use of Matlab in Control and in Communications Possibly other simulation environments (Labview, Comsol,
etc.) are briefly reviewed Combining Matlab and C (Optional, if course time is
sufficient)
6
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matlab-Imitating Freeware/Shareware Policy
The use of any kind of Matlab-imitating freeware/shareware such as Octave etc. is NOT allowed in this course
The use of any other licensed mathematical software, such as Maple, Mathematica or Mathcad etc., is NOT allowed in this course
Exercises or homeworks solved by using some other software than Matlab & Simulink are automatically ignored
We have an up-to-date Matlab license in the University of Vaasa, and the computer classes in Technobothnia are available
7
UNIVERSITY of VAASA Communications and Systems Engineering Group
Why Matlab?
It is not a toy The most common program for mathematical computation and
simulations in professional use
A huge amount of toolboxes
Compatibility – the program is de facto standard in professional and in research use File exchange Huge amount of Matlab-software including additional toolboxes
available (one must be careful, though)
8
UNIVERSITY of VAASA Communications and Systems Engineering Group
What is Matlab?
MATLAB (short for matrix laboratory) is a company run by the company MathWorks
It is computer software meant for numerical computations, it contains also it’s own programming language.
MATLAB provides opportunities for easy and efficient handling of matrices, functions, and visualization of data, implementation of algorithms, creation of user interfaces and interaction with the programs created with other languages.
In addition to the basic configuration of the software, there is available a number of additional tools (toolboxes), which allows specific areas of functionality, for example, or the possibility of symbolic computation.
9
UNIVERSITY of VAASA Communications and Systems Engineering Group
What is Simulink?
Simulink is a additional program for MATLAB that can be used to model, analyze and simulate dynamic systems in various technical areas.
Systems can be linear or non-linear and can be time dependent. The time dependence can be discrete, continuous, or a mixed
type. Simulink is a graphical user interface that allows the model
to be created using block diagrams, which consist of blocks and signal lines.
Simulink block diagrams may contain a variety of mathematical operations, MATLAB code and the inputs and outputs.
Block diagrams are hierarchical, allowing both top-down and a bottom-up approach, when the model is created.
10
UNIVERSITY of VAASA Communications and Systems Engineering Group
What is Simulink?
Common Simulink toolboxes include e.g. Communication System Toolbox Control System toolbox DSP System Toolbox Fuzzy logic toolbox Neural Network Toolbox 3D Animation Toolbox System Identification Toolbox Etc.
11
UNIVERSITY of VAASA Communications and Systems Engineering Group
Learn Matlab by yourself
There are Matlab training courses offered by Mathworks
https://se.mathworks.com/
https://matlabacademy.mathworks.com/R2015a/?s_tid=hp_mi_mlacademy_0515
https://se.mathworks.com/programs/nrd/buy-matlab-student.html?ref=ggl&s_eid=ppc_15474673282&q=%2Bmatlab%20%2Bstudent
12
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matlab
Many Matlab codes and Simulink systems are created all around the world and many have given their codes and models for the free use of others via Matlab file exchange (and other webpages) http://www.mathworks.se/matlabcentral/fileexchange/
Matlab examples are available in http://www.mathworks.se/products/matlab/examples.html http://www.mathworks.se/help/matlab/examples.html
Matlab tutorial videos http://www.mathworks.se/products/matlab/videos.html https://www.youtube.com/results?search_query=matlab
13
UNIVERSITY of VAASA Communications and Systems Engineering Group
Simulation
Simulation or simulating is an imitation of reality. The reality is the world around you. Man simulate reality in their
own world of imagination. An important and growing area of simulation is computer
simulation. Computer simulations are used by building an artificial reality in the computer that tries to mimic the real reality, as far as it can.
The simulation of the reality include, child play, many games and playing, imagination and the simulation of reality in physical or other models and their calculation (solar eclipses, exsosolar planet finding models etc.). In humans and mammals, a significant imitation of reality is a
game. Simulation is often cheaper than the reality (flight simulator
training), safer than the real situations (for a nuclear power plant simulator, playing war, a war game), and is often the only way to get information (atmosphere simulator to the greenhouse effect).
14
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
Modeling of the systems may have started a long time ago, at least from the Isaac Newton’s differential equations which he used to model physical systems
Usually computer simulations require coal to which the simulation aims or physical reality that the simulation tries to mimic
Typically we need to think about To what the model is used for The profitability of the modeling Users of the model What is modelled and calculated and how accurately How detailed model is needed
15
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
Usage of the model Model can be used for several purposes, e.g. to
predict the system behavior (weather, economy, population growth, climate change etc.)
Basic process model uses are To improve the existing systems Changing how the system is used Improve control system To design a new process To design a new manufacturing system or equipment
16
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
Profitability of the model In industry the profitability of the modeling and
simulation have to be justified Often simulation results are abstract and the
company lead requires proofs that simulation brings economic benefits and cost savings
Simulation is often used for decreasing the bugs in the system in advance
Profits of the model may include Direct benefits To increase the knowledge about the process Better control increases output Teaching the users to use system with the help of simulator
17
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
The users of the model In industry models are used by designers and
development managers Simulations could be used to introduce the idea for
management And for teaching staff how to use a new system To introduce the system to the customers
18
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
How detailed model is needed?
If we try to define the values for different components in the system we may need very accurate model E.g. fluid flow systems, building structure strenght
etc. (often static models)
When planning control systems models may be less accurate, but dynamic.
Models may contain transfer functions and state models and differential equations
Control systems usually require feedback loops
19
UNIVERSITY of VAASA Communications and Systems Engineering Group
The basics of modeling
Modeling project consist of Preplanning
Delimit, time table, resources, experiments Selecting the variables
What model is used for, theory, measurements needed Designing the model structure
Linear, nonlinear, real-time, state model, discrete, continuous
Designing the test plan (scenarios) Doing the experiments Analyzing the results To improve the model and testing
20
UNIVERSITY of VAASA Communications and Systems Engineering Group
Numeric calculus
Matlab is an Numerical calculation system Numerical analysis is the branch of mathematics that seeks
to find the approximate solution of mathematical problems that can not or need not be solved accurately.
Numerical methods are often applied in the needs of physics, for example, to solve the differential equations. Numerical methods such as equations, numerical solving of function, approximation and numerical integration.
An example of numerical analysis methods is forking which aims to find a continuous function zeros. Forking algorithm is as follows: Select number interval within which to examine the function,
and that the end points of the function has a different sign values . (* if search zeros)
Shortening of the interval at either end, so that the function gets a head to tail values of the endpoints of the interval.
Repeat until the desired accuracy is achieved.
21
UNIVERSITY of VAASA Communications and Systems Engineering Group
Numerical and Symbolic Computation
Example:
Symbolic computation computation in closed form by using mathematical symbols values of the variables are irrelevant (no rounding errors) great influence in development of mathematical theories programs supporting symbolic calculus can handle algebraic
expressions and calculate e.g. integrals and derivatives using symbols
sin 0.70714
Numerical computation:1
sin4 2
Symbolic computation:
1
0
1.7183xe dx 1
0
1xe dx e
22
UNIVERSITY of VAASA Communications and Systems Engineering Group
Numerical and Symbolic Calculus
Numerical calculus: e.g. pocket calculator: results are always approximate values
depending on the calculator’s internal computation accuracy risk: is the computation accuracy sufficient? numerical methods are efficient in solving complex problems it’s not even possible to solve all problems in closed form -
numerical calculus is needed (sometimes iterative) many integrals are difficult to solve in symbolic form whereas
numerical method would be more straightforward and faster therefore many practical applications (mathematical modeling,
simulation) usually exploit numerical calculus
23
UNIVERSITY of VAASA Communications and Systems Engineering Group
Numerical and Symbolic Calculus
The development of computer programs started at 1970’s the first programs were developed for
numerical calculus due to limited computing power
In the beginning it was difficult to use these programs operation based on programming e.g. Fortran (calculation of derivative
using parable interpolation) Due to increased computing power
graphical features and user-friendliness have become more popular
subroutine deriv1(h, y, dy, n)integer nreal h, hp, y(n), dy(n)hp = 0.5 / hC endpointsdy(1) = hp * (-3*y(1) + 4*y(2) - y(3))dy(n) = hp * (y(n-2) - 4*y(n-1) + 3 y(n))C midpointsdo i = 2,n-1dy(i) = hp * (y(i+1) - y(i-1))end doreturnend
24
UNIVERSITY of VAASA Communications and Systems Engineering Group
Numerical and Symbolic Calculus
It may not be possible to use numerical calculus program in real time computation in some process to be controlled reason: program intended for numerical computation is not
efficient enough in real time solution (if needed): implementation using C-programming
language programs are efficient in development because some of the
needed functions are already programmed
Some programs intended for symbolic calculus also support numerical calculus and vice versa
Symbolic calculus: Mathematica Maple MathCad
Numerical calculus: Matlab Excel Octave MATRIXx
25
UNIVERSITY of VAASA Communications and Systems Engineering Group
Lecture 2
Basics of Matlab Number representation Matrix operations Matlab data types Complex numbers in Matlab
26
UNIVERSITY of VAASA Communications and Systems Engineering Group
Number Representation,Computational Accuracy
27
UNIVERSITY of VAASA Communications and Systems Engineering Group
Bit and Byte
Computer’s memory handles numbers in bits and bytes
How are bits and bytes interpreted? e.g. integer data type
7
0
2iii
d b
0 1 2 3 4 5 6 71 2 1 2 0 2 0 2 0 2 0 2 1 2 0 2
1 2 0 0 0 0 64 0 67.
d
1000010 1
Byte = 8 bits
Bit
7 6 5 4 3 2 1 0
1000010 1
Byte = 8 bits
Bit
7 6 5 4 3 2 1 0
28
UNIVERSITY of VAASA Communications and Systems Engineering Group
Fixed and Floating Point Numbers
Fixed point numbers fixed amount of digits / number every number reserves memory space like an integer data type
(1-4 bytes) using four digits one can handle range [0, 9999] dot defines the accuracy of the number (12.81 versus 912.6)
Floating point numbers data type single represented in picture(4 bytes, range about
±10^38) exponent defines the order of magnitude and mantissa the
decimal part huge range can be represented in a very compact form (vs.
fixed point numbers) 012345678910111213141516171819202122232425262728293031
s Exponent n Mantissa m
s = sign bit
012345678910111213141516171819202122232425262728293031
s Exponent n Mantissa m
s = sign bit
29
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matlab GUI
User Interface (UI) Editor
30
UNIVERSITY of VAASA Communications and Systems Engineering Group
Finite Computation Accuracy
Handling numbers as floating point numbers can cause rounding errors in practice
Matlab:
» 1 5 0.2
ans =
0
» 1 0.2 0.2 0.2 0.2 0.2
ans =
5.5511e-017.
31
UNIVERSITY of VAASA Communications and Systems Engineering Group
Data Types in Matlab
char numeric
single (4 bytes) double (8 bytes, default data type) uint8 (1 byte) int64 (8 bytes) ...
struct cell
Addition information using command: help datatypes
32
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matrices and Character Arrays
33
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matrix
Matrix is an array of numbers consisting of horizontal rows and vertical columns
Individual numbers in matrix are called elements: for example element aij refers to the matrix element in row i and column j. Matrixes consisting of only one row or column are called row or column vectors accordingly.
1
2 1 - dimension
(column)vector
n
a
a na
a
11 12 1, 1 1,
12 22 2, 1 2,
,1 ,2 , 1 ,
row
column
matrix
m m
m m
n n n m n m
a a a a
a a a aa
a a a a
n m
34
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matrix in Matlab
Matrix is created by feeding the matrix elements one by one inside brackets ( [ ] )
Elements on the same row are separated by white space Rows are separated from each other with a semi-colon (;)
Matlab prints the return values to the command line if the row is not ended with a semi-colon
1 2 3
4 5 6A
>> A = [1 2 3; 4 5 6];
35
UNIVERSITY of VAASA Communications and Systems Engineering Group
Matrix in Matlab
Creating vectors in different ways 1st Way
2nd Way
vector = minimum value:step:maximum value 3rd Way
vector = linspace(minimum value, maximum value, number of elements)
a = [0 1 2 3 4 5] >> a = 0:5;
b = [1 3 5 7 9 11] >> b = 1:2:11;
c = [6 4.5 3 1.5 0] >> c = 6:-1.5:0;
a = [0 1 2 3 4 5] >> a = linspace(0, 5, 6);
a = [0 1 2 3 4 5] >> a = [0 1 2 3 4 5];
36
UNIVERSITY of VAASA Communications and Systems Engineering Group
Basic Matrix Arithmetic's
Transpose
Summation and subtraction
Multiplication with a scalar value
2 33 2
1 41 2 3
2 54 5 6
3 6
TA A
2 3
1 2 3
4 5 6A
2 3
7 8 9
10 11 12B
2 3
8 10 12
14 16 18A B
1 2 3
4 5 6A
2 3
4 5 6A
37
UNIVERSITY of VAASA Communications and Systems Engineering Group
Basic Matrix Arithmetic's
Matrix product The product of matrixes A and B is defined only if it the
following holds for matrix dimensions (dim)
dim , dim , dim A n x p B p x k C n x k
Esimerkki: MATLAB:
2 33 2
1 21 2 3 1 1 2 ( 1) 3 ( 2) 1 2 2 ( 1) 3 0 7 0
1 14 5 6 4 1 5 ( 1) 6 ( 2) 4 2 5 ( 1) 6 0 13 3
2 0
BA
C
» A = [1 2 3; 4 5 6]; » B = [1 2; -1 -1; -2 0]; » C = A*B
38
UNIVERSITY of VAASA Communications and Systems Engineering Group
Basic Matrix Arithmetic's
Matrix product is not commutative in general
Product’s zero-rule does not hold for matrix product
AB BA
1 2 1 1 5 1 2 2, ,
3 4 2 0 11 3 2 4A B AB BA
1 2 2 2 2 4, 0,
2 4 1 1 1 2A B AB BA
39
UNIVERSITY of VAASA Communications and Systems Engineering Group
Basic Matrix Arithmetic's in Matlab
Transpose using apostrophe (’) Summation and subtraction using plus- (+) and minus (-)
signs
But:
Two signs for product in Matlab: * and .* * is the matrix product .* is a product where matrix elements in the same row and
same column are multiplied with each other (element-wise product)
Same applies for division and involution / and ./ ^ and .^
40
UNIVERSITY of VAASA Communications and Systems Engineering Group
*
1 2
3 4
5 6
7 8
19 22
43 50
23 34
31 46
A
B
AB
BA
>> A = [1 2; 3 4];>> B = [5 6; 7 8];
>> A * B;>> B * A;
41
UNIVERSITY of VAASA Communications and Systems Engineering Group
*
1 2 3 , 4 5 6
4
1 2 3 5 32
6
1 4 5 6
2 4 5 6 8 10 12
3 12 15 18
T
T
a b
ab
ab
a b
Not possible
>> a * b’;
>> a’ * b;
42
UNIVERSITY of VAASA Communications and Systems Engineering Group
.*
1 2 5 6,
3 4 7 8
1 5 2 6 5 12 .*
3 7 4 8 21 32
1 2 3 , 4 5 6
.* 1 4 2 5 3 6 4 10 18
A B
A B
a b
a b
>> A .* B;
>> a .* b;
43
UNIVERSITY of VAASA Communications and Systems Engineering Group
Coupling of Matrices
Matrices can be coupled if the dimensions match
1 2 3
1 1 1
2 2 2
3 3 3
1 2, 5 6
3 4
1 2 1
3 4 2
5 6 3
Tx
X x x x
A b
AY x
b
>> x = [1 2 3]’;>> X = [x x x];
>> A = [1 2; 3 4];>> b = [5 6];>> Y = [[A; b] x];
44
UNIVERSITY of VAASA Communications and Systems Engineering Group
The Determinant of a Matrix
The determinant is an important concept in calculation of an inverse of a matrix
The determinant of a matrix is either real or complex number (scalar)
The determinant of a 2 x 2 –matrix is by definition
11 1211 22 12 21
21 22
, det a a
A A A a a a aa a
45
UNIVERSITY of VAASA Communications and Systems Engineering Group
11 12 1
21 22 2
1 2
1 det (cofactors)
n
n
n n nn
n n
i j
ij ij
a a a
a a aA
a a a
c A
Inverse of a Matrix
Matrix B is the inverse of matrix A , if The inverse of matrix A is denoted by Calculation rules
AB BA I 1A
11
1 1
1 1 1
1 1
1 ( scalar)
TT
A A
A A
AB B A
A A
1 adj ,
det when det 0
AA
AA
adj TA C
46
UNIVERSITY of VAASA Communications and Systems Engineering Group
/, \, ^-1 and inv
Esimerkki: MATLAB: 1 2
3 4A
» A = [1 2; 3 4];
5 6
7 8B
» B = [5 6; 7 8];
1 3 2
2 1AB
» A/B
tai » A*inv(B)
1 3 4
4 5A B
» A\B
tai » inv(A)*B
1 1 2
2 3BA
» B/A
tai » B*inv(A)
1 5 4
4 3B A
» B\A
tai » inv(B)*A 47
UNIVERSITY of VAASA Communications and Systems Engineering Group
Referring to Matrix Elements
Matrix is the basic data type in Matlab Data to be processed is usually stored in matrices Sometimes it’s of interest to manipulate only part of the data
stored in matrix. This interesting data has to be “picked out” of the matrix Plotting Analysis Data handling etc.
There may be need to remanipulate the data in matrix. In that case assignment is used, e.g. so that the part of the matrix data is replaced with new information
One has to know how to refer to desired matrix elements to be able to manipulate data properly
48
UNIVERSITY of VAASA Communications and Systems Engineering Group
Referring to Matrix Elements
Matrix elements are referred using parentheses first row(s) and then column(s)
The following can be used for referring: number vector end-command colon (:)
1 11 111 1111 11111
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 4444 44444
5 55 555 5555 55555
A
>> A(2,3)ans = 222
49
UNIVERSITY of VAASA Communications and Systems Engineering Group
Referring to Matrix Elements
Referring to individual elements using numbers – eg. A(2,3) It’s possible to refer to many rows/columns using vector
1 11 111 1111 11111
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 4444 44444
5 55 555 5555 55555
A
>> A(2,[1 3])ans = 2 222
>> A(2:4, 2)ans = 22 33 44
>> A(4, 1:2:5)ans = 4 444 44444
50
UNIVERSITY of VAASA Communications and Systems Engineering Group
Referring to Matrix Elements
The end-command is useful when referring to the last matrix element
1 2 3 4
1 11 111 1111 11111
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 4444 44444
5 55 555 5555 55555
x
A
>> x(end)ans = 4
>> x(end-1)ans = 3
>> A(4, 3:end)ans = 444 4444 44444
51
UNIVERSITY of VAASA Communications and Systems Engineering Group
Entire row or column can be referred using colon (:)
Referring to Matrix Elements
1 11 111 1111 11111
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 4444 44444
5 55 555 5555 55555
A
>> A(:,4)ans = 1111 2222 3333 4444 5555
>> A(2,:)ans = 2 22 222 2222 22222
52
UNIVERSITY of VAASA Communications and Systems Engineering Group
Referring to Matrix Elements
All the above situations can be combined with insertion
>> A(1,:) = [1 2 3 4 5];
>> A(4,4:end) = [8 9];
>> A(1:2:end,2) = 7;
1 2 3 4 5
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 4444 44444
5 55 555 5555 55555
A
1 2 3 4 5
2 22 222 2222 22222
3 33 333 3333 33333
4 44 444 8 9
5 55 555 5555 55555
A
1 7 3 4 5
2 22 222 2222 22222
3 7 333 3333 33333
4 44 444 8 9
5 7 555 5555 55555
A
53
UNIVERSITY of VAASA Communications and Systems Engineering Group
zeros & ones
Command zeros creates a matrix consisting of nothing but zeros This command can also be used for creating a vector
zeros(3)
zeros(3, 4)
zeros(1,2)
Same applies to command ones with the exception that the matrix contains only number ones
0 0 0
0 0 0
0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0
54
UNIVERSITY of VAASA Communications and Systems Engineering Group
eye
Command eye creates an identity matrix
eye(3)
eye(3,4)
1 0 0
0 1 0
0 0 1
1 0 0 0
0 1 0 0
0 0 1 0
55
UNIVERSITY of VAASA Communications and Systems Engineering Group
Useful Commands
56
UNIVERSITY of VAASA Communications and Systems Engineering Group
Useful Commands
Command Description
min(X) Returns the value (and the index) of the smallest element in vector X. If X happens to be a matrix, then min(X) returns the smallest values of every column (in a row vector).
max(X) Returns the value (and the index) of the greatest element in vector X. If X is matrix, then the greatest values of each column are returned as a row vector.
length(X) Returns the length of the vector (or the matrix).
size(X) Returns the amount of rows and columns in the matrix.
find(condition)
Returns the indices of those elements in which given condition is satisfied.
sort(X) Returns a matrix X in which elements in every column are sorted in ascending order. The indices are also returned in another matrix so the original matrix can be reformed from the return values.
57
UNIVERSITY of VAASA Communications and Systems Engineering Group
Useful Commands
Command Description
clc Clear screen, removes all writings from the command line
clear Clears all the variables currently defined in workspace
clear all Same as previous
clear A Clears the variable A
clear a b Clears variable a and b
who Tells what variables you have in your workspace
58
UNIVERSITY of VAASA Communications and Systems Engineering Group
min & max
A = [1 2 3 4 5 6]; min(A)
ans =
1 max(A)
ans =
6
1 2 3 4 5 6A
1 2 3
4 5 6
1 5 10
B
B = [A(:,1:3); A(:,4:6); [-1 5 10]]; min(B)
ans =
-1 2 3 [m, index] = max(B)
m =
4 5 10
index =
2 2 3
59
UNIVERSITY of VAASA Communications and Systems Engineering Group
length & size
>>A = [5 -1 3; 4 5 6; 8 -3 -5; 9 10 -11];>>length(A)
ans = 4
>>[rows, cols] = size(A)rows =
4cols =
3
5 1 3
4 5 6
8 3 5
9 10 11
A
for row_index = 1:rowsfor col_index = 1:cols
B(row_index, col_index) = row_index*col_index;end
end
1 2 3
2 4 6
3 6 9
4 8 12
B
60
UNIVERSITY of VAASA Communications and Systems Engineering Group
find & sort
A = [5 -1 3 4 5 6 8 -3 -5 9 10 -11]; indext = find(A < 0 | rem(A,3) == 0)
indext = 2 3 6 8 9 10 12
5 1 3 4 5 6 8 3 5 9 10 11A
[B, index] = sort(A)B =
-11 -5 -3 -1 3 4 5 5 6 8 9 10 index =
12 9 8 2 3 4 1 5 6 7 10 11 C = A(index)
C =-11 -5 -3 -1 3 4 5 5 6 8 9 10
61
UNIVERSITY of VAASA Communications and Systems Engineering Group
Solving a system of equations
System of equations
can be presented in matrix form
Solve the unknowns
2 3 6
7 15 8
x y
x y
2 3 6
7 15 8X YA
x
y
1 1 1
I
AX Y A A X A Y IX X A Y
3815 3 6 114 2.241 1 177 2 8 26 26 0.51det 51
51
XA
62
UNIVERSITY of VAASA Communications and Systems Engineering Group
Strings
Strings are char-arrays A string is created by writing the characters between
apostrophes (’)
Multiple strings can be concatenated by using brackets ([ ]) (compare to the concatenaton of matrixes)
Note the addition of a space (’ ’) between string1- and string2-variables
Compare with:
>> string3 = [string1 ’ ’ string2]string3 = Hello world! How do you do?
>> string1 = ’Hello world!’;>> string2 = ’How do you do?’;
>> string3 = [’string1’ ’ ’ ’string’]string3 = string1 string2
63
UNIVERSITY of VAASA Communications and Systems Engineering Group
Strings
Adding a number to the string The number must be transformed into string format by num2str-
function (number to string)
Or with shorter version (note the brackets, separate strings have to be concatenated with each other by using the brackets before they can be given as a parameter to the disp-function)
>> number = 200;>> message = [’I had ’ num2str(number) ’ rats in my car!’];>> disp(message);I had 200 rats in my car!
>> number = 200;>> disp([’I had ’ num2str(number) ’ rats in my car!’]);I had 200 rats in my car!
64
UNIVERSITY of VAASA Communications and Systems Engineering Group
Lecture 3
Basics of Matlab Complex numbers Basics of programming Basics of plotting
65
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex numbers
A set of complex numbers C is a natural extension of the real numbers. The complex number z is of the form
z = x + yi, where x and y are real numbers and i is the imaginary unit,
which can be labeled i2 = -1. The x of complex number is called a real part (Re (z)) and a number y, respectively, is the imaginary part (Im (z)).
Set of real numbers is a subset of the complex numbers obtained by setting the imaginary part of a complex number to zero: y = 0.
If x = 0, the complex number is called purely imaginary. Originally complex numbers were developed partly because
of the need to get a larger number of the polynomial equations to be solved. For example, the equation x2 + 1 = 0 has no real roots, because
x2 is positive for all real values of x. With complex numbers, however, we can found solutions x = + i and x = -i.
66
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex numbers
Complex numbers form a set of complex numbers , the numbers belonging to this group are of form
where x and y are real numbers
and
(real part) (imaginary
part)
z
Re
Im
y
x
z x yi
2 1i
Re
Im
z x
z y
67
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex numbers
Every complex number has
complement
conjugate
magnitude
inverse
Polar angle (argument)
z x yi
z x yi
z x yi
2 2z x y
12 2
1 z x yiz
z zz x y
arg z
z
Re
Im
y
x
φ
-y
-x
φ -y
x
φ
z
z
z
68
UNIVERSITY of VAASA Communications and Systems Engineering Group
The polar coordinate form
Complex numbers can be presented in polar coordinate form
, where
The relations between the polar coordinates (r, φ) and the Cartesian coordinates (x, y) of a complex number are
Euler’s formula
cos sinz r i
ja arg , tan , 0y
r z z xx
cos
sin
x r
y r
cos sin i ir i re z e
69
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex Matrix
The elements of the matrix can be complex
When dealing with complex matrix hermitting is used instead of transposing. The hermiting is defined as:
So the hermitted matrix is achieved by taking the complex conjugate and transpose
1 1
2 3 4 ( on imaginary unit)
3 1 2
i i
C i i i
i
H TC C
1 2 3 3
1 4 1 2H i iC
i i i
70
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex matrixes in Matlab
The elements of the matrix can be either real or complex numbers
The imaginary unit is either i or j When giving complex numbers as input note that the real
and imaginary parts must be written without space between them, otherwise they will be interpreted as different numbers.
a = [2+i 3-2i 4i] >> a = [2+i 3-2*i 4*i];
b = [2 i 3-2i 4i] >> b = [2 +i 3-2*i 4*i];
71
UNIVERSITY of VAASA Communications and Systems Engineering Group
Complex matrixes in Matlab
In Matlab matrix C is hermitted with command C’ and transposed with command C.’
>> C = [1+i 1-i; 2-3*i 4*i; 3 -1+2*i]C = 1 + i 1 - i 2 - 3i 0 + 4i 3 -1 + 2i>> C'ans = 1 - i 2 + 3i 3 1 + i 0 - 4i -1 - 2i>> C.'ans = 1 + i 2 - 3i 3 1 - i 0 + 4i -1 + 2i
72
UNIVERSITY of VAASA Communications and Systems Engineering Group
Programming and Command String Files (or scripts)
73
UNIVERSITY of VAASA Communications and Systems Engineering Group
Introduction
Matlab was first used by entering simple commands from the command line
This is not practical when implementing complex things requiring tens of commands or multiple repetitions of the same task. Reasons for this are: errors are easily made all the commands have to be entered once again when
detecting an error in the beginning of the command series entering commands by hand is very slow there will be no documentation of the entered commands (well,
Matlab command history remembers them for a while)
Programming helps!
74
UNIVERSITY of VAASA Communications and Systems Engineering Group
Branching
It’s often useful to make a choise between one or multiple alternatives
% marks a comment
if condition % do something...else % do something else...end
if (x > y) bigger = x;else bigger = y;end
75
UNIVERSITY of VAASA Communications and Systems Engineering Group
Creating Conditional Clauses
Relational operators in Matlab:
Example:
Operator Description < Smaller than > Bigger than <= Smaller than or equal to >= Bigger than or equal to == Equal to ~= Not equal to
» 1 < 2ans = 1
» 1 > 2ans = 0
76
UNIVERSITY of VAASA Communications and Systems Engineering Group
Note!
These operators are different: == “is equal to” = “is signed a value”
Character strings can not be compared using operator ==. Use strcmp-function instead
» 'cats' == 'dogs'ans = 0 0 0 1
» strcmp('cats', 'dogs')ans = 0» strcmp('cats', 'cats')ans = 1
77
UNIVERSITY of VAASA Communications and Systems Engineering Group
Creating Conditional Clauses
Logical operators in Matlab:
Examples: (true and false with small letters are predefined in Matlab)
Operator Description Priority ~ Logical NOT Greatest & Element-wise logical AND | Element-wise logical OR && AND || OR Smallest
» TRUE = 1; FALSE = 0;» TRUE & TRUEans = 1» TRUE & FALSEans = 0
» TRUE | FALSEans = 1» TRUE | TRUEans = 1
78
UNIVERSITY of VAASA Communications and Systems Engineering Group
Creating Conditional Clauses
& or &&? Right hand side of the clause is not evaluated if the left hand
side already gives the result of the clause when using &&-operator
Imagine a situation where b = 0 and you shoul calculate a/b (division by zero!)» a = 1;
» b = 0;» x = (b ~= 0) & (a/b > 18.5)Warning: Divide by zero.x = 0» x = (b ~= 0) && (a/b > 18.5)x = 0
79
UNIVERSITY of VAASA Communications and Systems Engineering Group
for-loop
for variable = initialValue:step:finalValue % do something...end
for index = -7:2:0 indexend
index = -7index = -5index = -3index= -1
80
UNIVERSITY of VAASA Communications and Systems Engineering Group
for-loop
[M, N] = size(X);sum = 0;for column = 1:N for row = 1:M sum = sum + X(row, column); endend
It’s possible to go through every matrix element by using two internal for-loops
81
UNIVERSITY of VAASA Communications and Systems Engineering Group
while-loop
while condition % do something...end
element = 1;while (element <= 10) x(element) = element; element = element + 1;end
82
UNIVERSITY of VAASA Communications and Systems Engineering Group
for vs. while
for-loop is used when it’s exactly known a priori how many repetitions are to be made E.g. going through every row and column in a matrix number of repetitions does not necessarily have to be a
constant for instance, the size of the matrix to go through can change from
one execution to another
while-loop is used when the number of repetitions is unknown in the beginning of the loop for example, the user feeds an unknown amount of numbers
83
UNIVERSITY of VAASA Communications and Systems Engineering Group
Question
How much is x?
Don’t do this at home! If you do CTRL C will help (terminate the run by user)
x = 0;while (2) x = x + 1;end
84
UNIVERSITY of VAASA Communications and Systems Engineering Group
break and continue
break-command exits the loop and program execution continues from the line after the loop
command continue forces the loop to start immediately from the beginning
85
UNIVERSITY of VAASA Communications and Systems Engineering Group
break and continue
index = 1;while (index < 5) if (index == 3) break; end; index index = index + 1;end;
index = 1;while (index < 5) if (index == 3) index = index + 1; continue; end; index index = index + 1;end;
index = 1index = 2
index = 1index = 2index = 4
Note write index to the comand line, what is the value? Why?
86
UNIVERSITY of VAASA Communications and Systems Engineering Group
Good Programming Practice
Program code should be easily read and understood easier to debug the errors easier to remember what the code was intended for after weeks
or months other people can more easily utilize the code in their programs
Code is easily read when: variables have descriptive names (do NOT use scandinavian
letters å, ä, ö) indentation and empty space is used properly it is well commented
87
UNIVERSITY of VAASA Communications and Systems Engineering Group
Good Programming Practice
% Initialize the variablesmatrixSize = 5;X = zeros(matrixSize);
% Let’s create a matrix in which diagonal elements% are 1 and elements over diagonal are 2 for row = 1:matrixSize for column = 1:matrixSize
%Checking if we’re on main diagonal if (row == column) % Yes – on main diagonal X(row, column) = 1; elseif (row < column) % Above main diagonal X(row, column) = 2; end endend
88
UNIVERSITY of VAASA Communications and Systems Engineering Group
Bad Programming Practice
x=5;X=zeros(x);for y=1:xfor z=1:xif y==zX(y,z)=1;elseif y>zX(y,z)=2;end,end,end
x=5;X=zeros(x);for y=1:x,for z=1:x,if y==z,X(y,z)=1;elseif y>z,X(y,z)=2;end,end,end
These are BAD examples
89
UNIVERSITY of VAASA Communications and Systems Engineering Group
Command String Files
Matlab command string file (script, macro) is a text file consisting of consecutive Matlab-function calls (commands). These files are of type *.m and they are called Matlab m-files.
Matlab executes the commands when the name of the command string file is written to the command line. These files utilize the existing variables in the workspace and store new variables created during execution to the workspace. These new variables can be used from the command line after the script execution has stopped.
90
UNIVERSITY of VAASA Communications and Systems Engineering Group
Plotting
91
UNIVERSITY of VAASA Communications and Systems Engineering Group
Basic Commands
Command Description
plot Plots the function/functions according to the parameters
loglog Otherwise the same as plot with the exception that the scales are logarithmic.
semilogx Logarithmic x-axis, normal y-axis.
semilogy Logarithmic y-axis, normal x-axis.
polar Polar coordinate representation.
Plotyy Same as plot but with a possibility to define two y-axis with different scales.
92
UNIVERSITY of VAASA Communications and Systems Engineering Group
Plotting Basic command: plot
First parameter: values in the x-axis
Second parameter: values in the y-axis
Additional parameters to customize the line type and colors.
Empty figure window: figure>> t = (0:0.1:10)';>> y = sin(2*pi*0.2*t);>> figure>> plot(t,y,'r.')>> hold on>> line([0 10],[0 0])>> xlabel(’Time (s)')>> ylabel('\it{sin(2\pift)}')>> title(’Graph')>> grid on
0 1 2 3 4 5 6 7 8 9 10-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Time (s)
sin(2
ft)
Graph
93
top related