Upload
lambert-fowler
View
218
Download
0
Tags:
Embed Size (px)
Citation preview
Signals and SystemsLaboratory 2013
• Teacher: Marek OssowskiTeacher: Marek [email protected]@p.lodz.plPhone: 42 6312515, Phone: 42 6312515, 501 673231501 673231Room 14, C3, Al.Politechniki 11Room 14, C3, Al.Politechniki 11Laboratory: Room 105, C3Laboratory: Room 105, C3
Department of Nonlinear Circuits and Systems,Department of Nonlinear Circuits and Systems,Institute of Electrical Engineering Systems (I12)Institute of Electrical Engineering Systems (I12)
Signals and SystemsLaboratory
• Teacher home page:Teacher home page:• http://matel/p.lodz.pl/wee/i12zet/mosso/http://matel/p.lodz.pl/wee/i12zet/mosso/
mosso_index.htmlmosso_index.html
• Files for today:Files for today:– Front pageFront page– Experiment 0Experiment 0– Experiment 1Experiment 1
Signals and SystemsLaboratory
• IntroductionIntroductionWhat is Matlab? A WORKSHOP.What is Matlab? A WORKSHOP.
• ExpExpeeriment riment 00–Elementary Matlab functions and Elementary Matlab functions and
operationsoperations– Basic Signals ManipulationsBasic Signals Manipulations– Systems identificationsSystems identifications
Signals and SystemsLaboratorySignals and SystemsLaboratory
• Experiment 1. Discrete and analog Experiment 1. Discrete and analog convolutionconvolution
• ExpExpeeriment riment 2. Properties of Discrete 2. Properties of Discrete Fourier Fourier Transform.Transform.
• Experiment 3. Spectral analysis of periodic Experiment 3. Spectral analysis of periodic signals. Fourier series.signals. Fourier series.
• Experiment 4. Fourier transform.Experiment 4. Fourier transform.• Experiment 5. Experiment 5. Analysis of dynamic LTI Analysis of dynamic LTI
systems usingsystems using state equations and Laplace state equations and Laplace transform concept.transform concept.
• Experiment 6. Z-transform. Digital filters.Experiment 6. Z-transform. Digital filters.
Before getting started…
• Acknowledgement: – This material was almost entirely created from information
compiled from various internet sources• It is available for download from SBEL website in PPT format for other
to be able to save, edit, and distribute as they see fit• Please let me know of any mistakes you find
– email me at [email protected], where mylastname is: negrut
• Purpose of the document:– You will not be able to say at the end of workshop that you know
MATLAB but rather that you have been exposed to MATLAB (I don’t know MATLAB myself, I’m just using it…:-)
– It is expected of you to use MATLAB’s “help” function a lot, as well as search the web for examples that come close to what you need
• You learn how to use MATLAB by using it, that’s why the start is maybe slow and at times frustrating
Contents1. First part of workshop
What is Matlab? MATLAB Components MATLAB Desktop Matrices
Numerical Arrays String Arrays
Importing and Exporting Data Elementary math with MATLAB
Contents Continued
2. Second part of workshop M-file Programming
Functions vs. Scripts Variable Type/Scope Debugging MATLAB functions Flow control in MATLAB
Other Tidbits Function minimization Root finding Solving ODE’s
Graphics Fundamentals Data Types most likely won’t have time for it
What is MATLAB?• Integrated software environment
– Computation– Visualization– Easy-to-use environment
• High-level language– Data types– Functions– Control flow statements– Input/output– Graphics– Object-oriented programming capabilities
MATLAB Parts
• High Level Development Environment
• Programming Language
• Graphics
• Toolboxes
• Application Program Interface
Toolboxes
• Collections of functions to solve problems from several application fields.– DSP (Digital Signal Processing) Toolbox– Image Toolbox– Wavelet Toolbox– Neural Network Toolbox– Fuzzy Logic Toolbox – Control Toolbox– Multibody Simulation Toolbox– And many others…
MATLAB 7x Desktop Tools
• Command Window• Command History• Help Browser• Workspace Browser• Editor/Debugger• To select what you
want to see, go under “Desktop” tab
MATLAB MATLAB 7x DESKTOP7x DESKTOP
Editor/DebuggerEditor/Debugger
InterpreterInterpreterCommand Window
CommandCommandHistoryHistory
HELP BROWSERHELP BROWSER
FigureFigureWindowWindowWokspaceWokspace
BrowserBrowser
Calculations at the Command Line
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = asin(y)
z =
1.5708
» a = 2;
» b = 5;
» a^b
ans =
32
» x = 5/2*pi;
» y = sin(x)
y =
1
» z = asin(y)
z =
1.5708
Results assigned to “ans” if name not specified
() parentheses for function inputs
Semicolon suppresses screen output
MATLAB as a calculator Assigning Variables
A Note about Workspace:Numbers stored in double-precision floating point format
» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470
» -5/(4.8+5.32)^2ans = -0.0488» (3+4i)*(3-4i)ans = 25» cos(pi/2)ans = 6.1230e-017» exp(acos(0.3))ans = 3.5470
General Functions
• whos: List current variables and their size• clear: Clear variables and functions from memory• cd: Change current working directory• dir: List files in directory• pwd: Tells you the current directory you work in• echo: Echo commands in M-files• format: Set output format (long, short, etc.)• diary(filename): Saves all the commands you type
in in a file in the current directory called filename
Getting help
• help command (>>help)
• lookfor command (>>lookfor)
• Help Browser (>>doc)
• helpwin command (>>helpwin)
• Search Engine
• Printable Documents– “Matlabroot\help\pdf_doc\”
• Link to The MathWorks
Matrices• Entering and Generating Matrices• Subscripts• Scalar Expansion• Concatenation• Deleting Rows and Columns• Array Extraction• Matrix and Array Multiplication
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
» a=[1 2;3 4]
a =
1 2
3 4
» b=[-2.8, sqrt(-7), (3+5+6)*3/4]
b =
-2.8000 0 + 2.6458i 10.5000
» b(2,5) = 23
b =
-2.8000 0 + 2.6458i 10.5000 0 0
0 0 0 0 23.0000
•Any MATLAB expression can be entered as a matrix element (internally, it is regarded as such)
•In MATLAB, the arrays are always rectangular
Entering Numeric Arrays
NOTE: 1) Row separatorsemicolon (;)
2) Column separatorspace OR comma (,)
Use square brackets [ ]
The Matrix in MATLAB
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
Rows (m) 3
4
5
Columns(n)
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A = A (2,4)
A (17)
Rectangular Matrix:Scalar: 1-by-1 arrayVector: m-by-1 array
1-by-n arrayMatrix: m-by-n array
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
» w=[1 2;3 4] + 5w = 6 7 8 9» x = 1:5
x = 1 2 3 4 5» y = 2:-0.5:0
y = 2.0000 1.5000 1.0000 0.5000 0 » z = rand(2,4)
z =
0.9501 0.6068 0.8913 0.4565 0.2311 0.4860 0.7621 0.0185
Scalar expansion
Creating sequences:colon operator (:)
Utility functions for creating matrices.
Entering Numeric Arrays
Examples (Entering Numeric Arrays)
• Enter the matrix:
• enter the row vector:
• Enter the column vector :
543
432
321
A
9876B
9
8
7
6
C
Numerical Array Concatenation
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
» a=[1 2;3 4]
a =
1 2
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]cat_a = 1 2 2 4 3 4 6 8 3 6 4 8 9 12 12 16 5 10 6 12 15 20 18 24
Use [ ] to combine existing arrays as matrix “elements”
Row separator:semicolon (;)
Column separator:space / comma (,)
Use square brackets [ ]
Note:The resulting matrix must be rectangular
4*a
Deleting Rows and Columns
» A=[1 5 9;4 3 2.5; 0.1 10 3i+1]
A =
1.0000 5.0000 9.0000
4.0000 3.0000 2.5000
0.1000 10.0000 1.0000+3.0000i
» A(:,2)=[]
A =
1.0000 9.0000
4.0000 2.5000
0.1000 1.0000 + 3.0000i
» A(2,2)=[]
??? Indexed empty matrix assignment is not allowed.
» A=[1 5 9;4 3 2.5; 0.1 10 3i+1]
A =
1.0000 5.0000 9.0000
4.0000 3.0000 2.5000
0.1000 10.0000 1.0000+3.0000i
» A(:,2)=[]
A =
1.0000 9.0000
4.0000 2.5000
0.1000 1.0000 + 3.0000i
» A(2,2)=[]
??? Indexed empty matrix assignment is not allowed.
Array Subscripting / Indexing
4 10 1 6 2
8 1.2 9 4 25
7.2 5 7 1 11
0 0.5 4 5 56
23 83 13 0 10
1
2
3
4
5
1 2 3 4 51 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
A =
A(3,1)A(3)
A(1:5,5)A(:,5) A(21:25)
A(4:5,2:3)A([9 14;10 15])
A(1:end,end) A(:,end)A(21:end)’
Matrix Multiplication» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10 26 26 26
» a = [1 2 3 4; 5 6 7 8];
» b = ones(4,3);
» c = a*b
c =
10 10 10 26 26 26
[2x4]
[4x3]
[2x4]*[4x3] [2x3]
a(2nd row).b(3rd column)
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16 5 12 21 32
» a = [1 2 3 4; 5 6 7 8];
» b = [1:4; 1:4];
» c = a.*b
c =
1 4 9 16 5 12 21 32 c(2,4) = a(2,4)*b(2,4)
Array Multiplication
Matrix Manipulation Functions• zeros: Create an array of all zeros
• ones: Create an array of all ones
• eye: Identity Matrix
• rand: Uniformly distributed random numbers
• diag: Diagonal matrices and diagonal of a matrix
• size: Return array dimensions • fliplr: Flip matrices left-right
• flipud: Flip matrices up and down
• repmat: Replicate and tile a matrix
Matrix Manipulation Functions
• transpose (’): Transpose matrix • rot90: rotate matrix 90
• tril: Lower triangular part of a matrix
• triu: Upper triangular part of a matrix
• cross: Vector cross product
• dot: Vector dot product
• det: Matrix determinant
• inv: Matrix inverse
• eig: Evaluate eigenvalues and eigenvectors
• rank: Rank of matrix
Exercise 1 (5 minutes)Define a matrix A of dimension 2 by 4 whose (i,j) entry is A(i,j)=i+jExtract two 2 by 2 matrices A1 and A2 out of the matrix A. A1 contains the first two columns of A, A2 contains the last two columns of ACompute the matrix B to be the sum of A1 and A2Compute the eigenvalues and eigenvectors of B Solve the linear system Bx=b, where b has all the entries equal to 1Compute the determinant of BCompute the inverse of BCompute the condition number of BNOTE: Use only MATLAB native functions for all operations
Character Arrays (Strings)• Created using single quote delimiter (')
• Each character is a separate matrix element (16 bits of memory per character)
• Indexing same as for numeric arrays
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
» str = 'Hi there,'
str =
Hi there,
» str2 = 'Isn''t MATLAB great?'
str2 =
Isn't MATLAB great?
1x9 vectorstr = H i t h e r e ,
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =Hi there, Everyone! » str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]new_str2 =Hi there, Everyone!Isn't MATLAB great?
» str ='Hi there,';
» str1='Everyone!';
» new_str=[str, ' ', str1]
new_str =Hi there, Everyone! » str2 = 'Isn''t MATLAB great?';
» new_str2=[new_str; str2]new_str2 =Hi there, Everyone!Isn't MATLAB great?
1x19 vector
1x9 vectors
String Array Concatenation
Using [ ] operator:Each row must be same length
Row separator:semicolon (;)
Column separator:space / comma (,)
For strings of different length:• STRVCAT• char
» new_str3 = strvcat(str, str2)new_str3 =Hi there, Isn't MATLAB great?
» new_str3 = strvcat(str, str2)new_str3 =Hi there, Isn't MATLAB great?
2x19 matrix
2x19 matrix(zero padded)
1x19 vectors
Working with String Arrays
• String Comparisons– strcmp: compare whole strings– strncmp: compare first ‘N’ characters– findstr: finds substring within a larger string
• Converting between numeric & string arrays:– num2str: convert from numeric to string array– str2num: convert from string to numeric array
Logical Operations
» Mass = [-2 10 NaN 30 -11 Inf 31];» each_pos = Mass>=0each_pos = 0 1 0 1 0 1 1» all_pos = all(Mass>=0)all_pos = 0» all_pos = any(Mass>=0)all_pos = 1» pos_fin = (Mass>=0)&(isfinite(Mass))pos_fin = 0 1 0 1 0 0 1
» Mass = [-2 10 NaN 30 -11 Inf 31];» each_pos = Mass>=0each_pos = 0 1 0 1 0 1 1» all_pos = all(Mass>=0)all_pos = 0» all_pos = any(Mass>=0)all_pos = 1» pos_fin = (Mass>=0)&(isfinite(Mass))pos_fin = 0 1 0 1 0 0 1
= = equal to
> greater than
< less than
>= Greater or equal
<= less or equal
~ not
& and
| or
isfinite(), etc. . . .
all(), any()
find
Note:• 1 = TRUE• 0 = FALSE
Elementary Math Function
• abs, sign: Absolute value and Signum Function
• sin, cos, asin, acos…: Triangular functions• exp, log, log10: Exponential, Natural and
Common (base 10) logarithm• ceil, floor: Round toward infinities• fix: Round toward zero
Elementary Math Function
• round: Round to the nearest integer
• gcd: Greatest common devisor
• lcm: Least common multiple
• sqrt: Square root function
• real, imag: Real and Image part of complex
• rem: Remainder after division
Elementary Math Function
• max, min: Maximum and Minimum of arrays• mean, median: Average and Median of arrays • std, var: Standard deviation and variance • sort: Sort elements in ascending order• sum, prod: Summation & Product of Elements• trapz: Trapezoidal numerical integration• cumsum, cumprod: Cumulative sum, product• diff, gradient: Differences and Numerical
Gradient
Polynomials and Interpolation
• Polynomials – Representing– Roots (>> roots)
– Evaluation (>> polyval)
– Derivatives (>> polyder)
– Curve Fitting (>> polyfit)
– Partial Fraction Expansion (>>residue)
• Interpolation– One-Dimensional (interp1)– Two-Dimensional (interp2)
polysam=[1 0 0 8];roots(polysam)ans = -2.0000 1.0000 + 1.7321i 1.0000 - 1.7321ipolyval(polysam,[0 1 2.5 4 6.5])ans = 8.0000 9.0000 23.6250 72.0000 282.6250polyder(polysam)ans = 3 0 0[r p k]=residue(polysam,[1 2 1])r = 3 7p = -1 -1k = 1 -2
polysam=[1 0 0 8];roots(polysam)ans = -2.0000 1.0000 + 1.7321i 1.0000 - 1.7321ipolyval(polysam,[0 1 2.5 4 6.5])ans = 8.0000 9.0000 23.6250 72.0000 282.6250polyder(polysam)ans = 3 0 0[r p k]=residue(polysam,[1 2 1])r = 3 7p = -1 -1k = 1 -2
Example
x = [0: 0.1: 2.5];y = erf(x); p = polyfit(x,y,6)p = 0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004
x = [0: 0.1: 2.5];y = erf(x); p = polyfit(x,y,6)p = 0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004
Example
interp1(x,y,[0.45 0.95 2.2 3.0])ans = 0.4744 0.8198 0.9981 NaN
interp1(x,y,[0.45 0.95 2.2 3.0])ans = 0.4744 0.8198 0.9981 NaN
Exercise 2 (5 minutes)
• Let x be an array of values from 0 to 2, equally spaced by 0.01– Compute the array of exponentials corresponding to
the values stored in x– Find the polynomial p of degree 5 that is the best least
square approximation to y on the given interval [0,2]– Evaluate the polynomial p at the values of x, and
compute the error z with respect to the array y– Interpolate the (x,z) data to approximate the value of
the error in interpolation at the point .9995
Topics discussed…
• The concept of m-file in MATLAB
• Script versus function files
• The concept of workspace
• Variables in MATLAB– Type of a variable– Scope of a variable
• Flow control in MATLAB
• The Editor/Debugger
Before getting lost in details…
• Obtaining User Input– “input” - Prompting the user for input
>> apls = input( ‘How many apples? ‘ )
– “keyboard” - Pausing During Execution (when in M-file)
• Shell Escape Functions (! Operator)
• Optimizing MATLAB Code– Vectorizing loops– Preallocating Arrays
Function M-file
function r = ourrank(X,tol)
% rank of a matrix
s = svd(X);
if (nargin == 1)
tol = max(size(X)) * s(1)* eps;
end
r = sum(s > tol);
function r = ourrank(X,tol)
% rank of a matrix
s = svd(X);
if (nargin == 1)
tol = max(size(X)) * s(1)* eps;
end
r = sum(s > tol);
function [mean,stdev] = ourstat(x)[m,n] = size(x);if m == 1
m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);
function [mean,stdev] = ourstat(x)[m,n] = size(x);if m == 1
m = n;endmean = sum(x)/m;stdev = sqrt(sum(x.^2)/m – mean.^2);
Multiple Input Argumentsuse ( )
Multiple Output Arguments, use [ ]
»r=ourrank(rand(5),.1);
»[m std]=ourstat(1:9);
Basic Parts of a Function M-File
function y = mean (x)
% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
m = n;
end
y = sum(x)/m;
Output Arguments Input ArgumentsFunction Name
Online Help
Function Code
Script and Function Files
• Script Files• Work as though you typed commands into
MATLAB prompt
• Variable are stored in MATLAB workspace
• Function Files• Let you make your own MATLAB Functions
• All variables within a function are local
• All information must be passed to functions as parameters
• Subfunctions are supported
The concept of Workspace
• At any time in a MATLAB session, the code has a workspace associated with it
• The workspace is like a sandbox in which you find yourself at a certain point of executing MATLAB
• Base Workspace: the workspace in which you live when you execute commands from prompt
• Remarks:
• Each MATLAB function has its own workspace (its own sandbox)
• A function invoked from a calling function has its own and separate workspace (sandbox)
• A script does not lead to a new workspace (unlike a function), but lives in the workspace from which it was invoked
Variable Types in MATLAB• Local Variables
• In general, a variable in MATLAB has local scope, that is, it’s only available in its workspace
• The variable disappears when the workspace ceases to exist
• Recall that a script does not define a new workspace – be careful, otherwise you can step on variables defined at the level where the script is invoked
• Since a function defines its own workspace, a variable defined in a function is local to that function
• Variables defined outside the function should be passed to function as arguments. Furthermore, the arguments are passed by value
• Every variable defined in the subroutine, if to be used outside the body of the function should be returned back to the calling workspace
Variable Types in MATLAB• Global Variables
• These are variables that are available in multiple workspaces
• They have to be explicitly declared as being global
• Not going to expand on this, since using global variables are a bad programming practice
• Note on returning values from a function• Since all variables are local and input arguments are passed by value,
when returning from a function a variable that is modified in the function will not appear as modified in the calling workspace unless the variable is either global, or declared a return variable for that function
if ((attendance >= 0.90) & (grade_average >= 60))
pass = 1;
end;
if ((attendance >= 0.90) & (grade_average >= 60))
pass = 1;
end;
eps = 1;
while (1+eps) > 1
eps = eps/2;
end
eps = eps*2
eps = 1;
while (1+eps) > 1
eps = eps/2;
end
eps = eps*2
if Statement
while Loops
Flow Control Statements
a = zeros(k,k) % Preallocate matrix
for m = 1:k
for n = 1:k
a(m,n) = 1/(m+n -1);
end
end
a = zeros(k,k) % Preallocate matrix
for m = 1:k
for n = 1:k
a(m,n) = 1/(m+n -1);
end
end
method = 'Bilinear';
switch lower(method)
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
otherwise
disp('Unknown method.')
end
Method is linear
method = 'Bilinear';
switch lower(method)
case {'linear','bilinear'}
disp('Method is linear')
case 'cubic'
disp('Method is cubic')
otherwise
disp('Unknown method.')
end
Method is linear
for Loop:
switch Statement:
Flow Control Statements
Editing and Debugging M-Files
• The Editor/Debugger
• Debugging M-Files– Types of Errors (Syntax Error and Runtime Error)
– Using keyboard and “ ; ” statement
– Setting Breakpoints
– Stepping Through Continue, Go Until Cursor, Step, Step In, Step Out
– Examining Values Selecting the Workspace Viewing Datatips in the Editor/Debugger Evaluating a Selection
Importing and Exporting Data
• Using the Import Wizard
• Using Save and Load command
load fnameload fname x y zload fname -asciiload fname -mat
load fnameload fname x y zload fname -asciiload fname -mat
save fnamesave fname x y zsave fname -asciisave fname -mat
save fnamesave fname x y zsave fname -asciisave fname -mat
•Read formatted data, reusing the format string N times.
•Import and Exporting Numeric Data with General ASCII delimited files
»[A1…An]=textread(filename,format,N)»[A1…An]=textread(filename,format,N)
Input/Output for Text File
» M = dlmread(filename,delimiter,range)» M = dlmread(filename,delimiter,range)
Input/Output for Binary File
• fopen: Open a file for input/output
• fclose: Close one or more open files
• fread: Read binary data from file
• fwrite: Write binary data to a file
• fseek: Set file position indicator» fid= fopen('mydata.bin' , 'wb');» fwrite (fid,eye(5) , 'int32');» fclose (fid);» fid= fopen('mydata.bin' , 'rb');» M= fread(fid, [5 5], 'int32')» fclose (fid);
» fid= fopen('mydata.bin' , 'wb');» fwrite (fid,eye(5) , 'int32');» fclose (fid);» fid= fopen('mydata.bin' , 'rb');» M= fread(fid, [5 5], 'int32')» fclose (fid);
Exercise 3: A debug session (10 minutes)
• Use the function demoBisect provided on the next slide to run a debug session– Save the MATLAB function to a file called
demoBisect.m in the current directory– Call once the demoBisect.m from the MATLAB
prompt to see how it works>>help demoBisect>>demoBisect(0, 5, 30)– Place some breakpoints and run a debug session
• Step through the code, and check the values of variables• Use the MATLAB prompt to echo variables• Use dbstep, dbcont, dbquit commands
function xm = demoBisect(xleft,xright,n)% demoBisect Use bisection to find the root of x - x^(1/3) - 2%% Synopsis: x = demoBisect(xleft,xright)% x = demoBisect(xleft,xright,n)%% Input: xleft,xright = left and right brackets of the root% n = (optional) number of iterations; default: n = 15%% Output: x = estimate of the root
if nargin<3, n=15; end % Default number of iterationsa = xleft; b = xright; % Copy original bracket to local variablesfa = a - a^(1/3) - 2; % Initial values of f(a) and f(b)fb = b - b^(1/3) - 2;fprintf(' k a xmid b f(xmid)\n');
for k=1:n xm = a + 0.5*(b-a); % Minimize roundoff in computing the midpoint fm = xm - xm^(1/3) - 2; % f(x) at midpoint fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm); if sign(fm)==sign(fa) % Root lies in interval [xm,b], replace a a = xm; fa = fm; else % Root lies in interval [a,xm], replace b b = xm; fb = fm; endend
Nonlinear Numerical Functions
• inline function » f = inline('3*sin(2*x.^2)','x')
f = Inline function: f(x) = 3*sin(2*x.^2)» f(2)ans = 2.9681
» f = inline('3*sin(2*x.^2)','x')
f = Inline function: f(x) = 3*sin(2*x.^2)» f(2)ans = 2.9681
Use char function to convert inline object to string
• Numerical Integration using quad» Q = quad('1./(x.^3-2*x-5)',0,2); » F = inline('1./(x.^3-2*x-5)'); » Q = quad(F,0,2);» Q = quad('myfun',0,2)
» Q = quad('1./(x.^3-2*x-5)',0,2); » F = inline('1./(x.^3-2*x-5)'); » Q = quad(F,0,2);» Q = quad('myfun',0,2)
function y = myfun(x)
y = 1./(x.^3-2*x-5);
Note:quad function use adaptive Simpson quadrature
Nonlinear Numerical Functions
• fzero finds a zero of a single variable function
– fun is inline function or m-function
• fminbnd minimize a single variable function on a fixed interval. x1<x<x2
• fminsearch minimize a several variable function
• Use optimset to determine options parameter.
[x,fval]= fzero(fun,x0,options)
[x,fval]= fminbnd(fun,x1,x2,options)
[x,fval]= fminsearch(fun,x0,options)
options = optimset('param1',value1,...)
Ordinary Differential Equations(Initial Value Problem)
• An explicit ODE with initial value:
• Using ode45 for non-stiff functions and ode23t for stiff functions.
[t,y] = solver(odefun,tspan,y0,options)
[initialtime finaltime]
Initialvluefunction dydt = odefun(t,y)
•Use odeset to define options parameter
ODE Example:
» [t,y]=ode45('myfunc',[0 20],[2;0])» [t,y]=ode45('myfunc',[0 20],[2;0])
function dydt=myfunc(t,y)dydt=zeros(2,1);dydt(1)=y(2);dydt(2)=(1-y(1)^2)*y(2)-y(1);
0 2 4 6 8 10 12 14 16 18 20-3
-2
-1
0
1
2
3
Note:Help on odeset to set options for more accuracy and other useful utilities like drawing results during solving.
Example 4: Using ODE45 (5 minutes)
• Use the example on the previous page to solve the slightly different IVP on the interval [0,20] seconds:
21 1 1 1
1
1
(1 0.9 ) 0
(0) 2
(0) 0
y y y y
y
y
Graphics and Plotting in MATLAB
• Basic Plotting– plot, title, xlabel, grid, legend, hold, axis
• Editing Plots– Property Editor
• Mesh and Surface Plots– meshgrid, mesh, surf, colorbar, patch, hidden
• Handle Graphics
2-D Plotting
Syntax:
Example:
plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)
x=[0:0.1:2*pi];y=sin(x);z=cos(x);plot(x,y,x,z,'linewidth',2)title('Sample Plot','fontsize',14);xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);legend('Y data','Z data')grid on
x=[0:0.1:2*pi];y=sin(x);z=cos(x);plot(x,y,x,z,'linewidth',2)title('Sample Plot','fontsize',14);xlabel('X values','fontsize',14);ylabel('Y values','fontsize',14);legend('Y data','Z data')grid on
color
line marker
Displaying Multiple Plots
• Nomenclature: – Figure window – the window in which MATLAB displays plots– Plot – a region of a window in which a curve (or surface) is
displayed
• Three typical ways to display multiple curves in MATLAB (other combinations are possible…)– One figure contains one plot that contains multiple curves
• Requires the use of the command “hold” (see MATLAB help)
– One figure contains multiple plots, each plot containing one curve• Requires the use of the command “subplot”
– Multiple figures, each containing one or more plots, each containing one or more curves
• Requires the use of the command “figure” and possibly “subplot”
SubplotsSyntax:
»subplot(2,2,1);
» …
»subplot(2,2,2)
» ...
»subplot(2,2,3)
» ...
»subplot(2,2,4)
» ...
»subplot(2,2,1);
» …
»subplot(2,2,2)
» ...
»subplot(2,2,3)
» ...
»subplot(2,2,4)
» ...
subplot(rows,cols,index)subplot(rows,cols,index)
The “figure” Command
• Use if you want to have several figures open for plotting
• The command by itself creates a new figure window and returns its handle>> figure
• If you have 20 figures open and want to make figure 9 the default one (this is where the next plot command will display a curve) use >> figure(9)>> plot(…)
• Use the command close(9) if you want to close figure 9 in case you don’t need it anymore
Surface Plot Examplex = 0:0.1:2;y = 0:0.1:2;[xx, yy] = meshgrid(x,y);zz=sin(xx.^2+yy.^2);surf(xx,yy,zz)xlabel('X axes')ylabel('Y axes')
x = 0:0.1:2;y = 0:0.1:2;[xx, yy] = meshgrid(x,y);zz=sin(xx.^2+yy.^2);surf(xx,yy,zz)xlabel('X axes')ylabel('Y axes')
Handle Graphics
• Graphics in MATLAB consist of objects:– root, figure, axes, image, line, patch,
rectangle, surface, text, light• Creating Objects• Setting Object Properties Upon
Creation• Obtaining an Object’s Handles • Knowing Object Properties• Modifying Object Properties
– Using Command Line– Using Property Editor
Rootobject
Figureobject
UIControlobjects
UIMenuobjects
Axes object
Figureobject
Surfaceobject
Lineobjects
Textobjects
UIControlobjects
UIMenuobjects
Axes object
Figureobject
Graphics Objects
1. Upon Creation
2. Utility Functions 0 - root object handle gcf - current figure handle gca - current axis handle gco - current object handle
3. FINDOBJ
Obtaining an Object’s Handle
h_obj = findobj(h_parent, 'Property', 'Value', ...)
h_line = plot(x_data, y_data, ...)
What is the current object? • Last object created
OR• Last object clicked
Default = 0 (root object)
Modifying Object Properties
• Obtaining a list of current properties:
• Obtaining a list of settable properties:
• Modifying an object’s properties Using Command Line
Using Property Editor
get(h_object)
set(h_object)
set(h_object,'PropertyName','New_Value',...)
Graphical User Interface
• What is GUI?
• What is figure and *.fig file?
• Using guide command
• GUI controls
• GUI menus
Multidimensional Arrays
» A = pascal(4);» A(:,:,2) = magic(4)A(:,:,1) = 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20A(:,:,2) = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1» A(:,:,9) =
diag(ones(1,4));
» A = pascal(4);» A(:,:,2) = magic(4)A(:,:,1) = 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20A(:,:,2) = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1» A(:,:,9) =
diag(ones(1,4));
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
Page N
Page 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
The first references array dimension 1, the row.
The second references dimension 2, the column.
The third references dimension 3, The page.
Structures•Arrays with named data containers called fields.
» patient.name='John Doe';» patient.billing = 127.00;» patient.test= [79 75 73; 180 178 177.5; 220 210 205];
» patient.name='John Doe';» patient.billing = 127.00;» patient.test= [79 75 73; 180 178 177.5; 220 210 205];
•Also, Build structure arrays using the struct function.•Array of structures
» patient(2).name='Katty Thomson';» Patient(2).billing = 100.00;» Patient(2).test= [69 25 33; 120 128 177.5; 220
210 205];
» patient(2).name='Katty Thomson';» Patient(2).billing = 100.00;» Patient(2).test= [69 25 33; 120 128 177.5; 220
210 205];
Cell Arrays•Array for which the elements are cells and can hold
other MATLAB arrays of different types.
» A(1,1) = {[1 4 3;0 5 8;7 2 9]};» A(1,2) = {'Anne Smith'};» A(2,1) = {3+7i};» A(2,2) = {-pi:pi/10:pi};
» A(1,1) = {[1 4 3;0 5 8;7 2 9]};» A(1,2) = {'Anne Smith'};» A(2,1) = {3+7i};» A(2,2) = {-pi:pi/10:pi};
•Using braces {} to point to elements of cell array
•Using celldisp function to display cell array
Conclusion
Matlab is a language of technical computing.
Matlab, a high performance software, a high-level language
Matlab supports GUI, API, and …
Matlab Toolboxes best fits different applications
Matlab …
Getting more help
• Contact http://www.mathworks.com/support • You can find more help and FAQ about
mathworks products on this page.• Contact comp.soft-sys.matlab Newsgroup• Use google to find more information (like the
content of this presentation, in the first place)