Control Engineering with MATLAB chibum@seoultech.ac.kr
Oultine MATLAB introduction MATLAB basics MATLAB/Control systems toolbox
MATLAB Cleve Moler (mathematician, C.S. Professor, co-author of LINPACK), started developing MATLAB in the late 70s to give students easy access to LINPACK(Numerical Library) MATLAB ("Matrix Laboratory") became popular interactive easy input, output operations on a whole vector or matrix at once Jack Little saw MATLAB in a lecture by Cleve Moler at Stanford University and founded The Mathworks rewrote MATLAB in C added "M-files" (stored programs) many new features and libraries
MATLAB Extensible using Toolboxes or user-contributed programs called M-files. MATLAB "M-Files" MATLAB "Toolboxes" Interactive user interface; hides boring details MATLAB Modular, reusable software components Standard base platform Linear Algebra Libraries FORTRAN Compiler
Matlab Today A standard tool in both professional and academic use "Toolboxes" providing functions for many applications: control systems identification neural networks bio-informatics statistics and time-series analysis Symbolic mathematics (symbolic toolboxe, mupad) Simulink: GUI based simulation tool
MATLAB Toolboxes MATLAB Math and optimization Signal Processing and communications Simulink Product Family.. Control System Design and Analysis Toolboxes Optimization Symbolic Math Partial Diff. Eq. Toolboxes Signal Processing Communications Filter Design Filter Design HDL Coder Simulink Simulink Accelerator Simulink Report Generator Toolboxes Simulink Control Design Simulink Response Simulink Parameter
MATLAB and Control MATLAB-Toolboxes for Control Linear Control Nonlinear Control Identification Control System Toolbox Simulink Mu Toolbox Nonlinear Control Toolbox Fuzzy Toolbox Simulink Identification Toolbox Frequency-Domain ID Toolbox Simulink
MATLAB Environment Workspace Window 사용된변수들에대한정보제공 Editor Window 프로그램작성및편집 Toolbar 그림창그래프명령어가실행되면자동생성됨 Command History Window 명령어창에서입력된명령어들이기록되어있음
MATLAB Help Windows
Command Window 명령어와명령어사이에콤마 (,) 를넣어여러명령어를한줄에표시가가능하다. Enter 키를누르면명령어를수행한다. 위쪽방향키 ( ) 를누를때마다이전에입력했던명령어가역순으로나타난다. 명령어가길어서한줄에쓸수없는경우, 마침표세개... 을찍고 Enter 키를누르면다음줄에서이어서쓸수있다 기호 (%) 를명령어줄제일앞에쓰면주석문 (comment) 으로지정된다. clc 는명령어창에서입력한명령어들과결과출력물들을지워서명령어창을깨끗이만든다. 명령어끝에세미콜론 ( ; ) 을붙이면출력이표시되지않는다.
MATLAB m 파일의생성 MATLAB 메뉴의 File New M-File을선택하거나, 메뉴밑의 Toolbar에서아이콘을선택하면, Editor 창이실행된다. 이 Editor 창에서프로그램을작성하고예를들어 test.m으로저장을한후, 매트랩명령어창에서 >> test 라고입력하면프로그램이수행된다.
행렬의입력방법 직각수치행렬을기본적인자료의형식으로취급 차원의선언이나형선언이불필요, 컴퓨터가자동적으로저장공간을할당 행렬의원소 : 실수, 복소수, 문자 행렬입력방식 명령창 내부명령또는함수들을사용하여행렬을생성 M-파일내에서행렬을구성 외부의자료파일로부터행렬을불러들임 행렬입력의규칙 원소들은빈칸또는쉼표를사용하여분리한다. 전체원소들은대괄호 ( [ ] ) 로감싼다. 원소의끝에세미콜론 ( ; ) 을붙이면한행의종료를의미한다.
행렬의덧셈과뺄셈 + 와 - 기호사용 두행렬또는벡터의차원이같아야함 각행렬의같은위치, 즉행렬상의색인이같은원소끼리연산 예외적으로 1 1 행렬인스칼라의경우에는어떤한행렬이나벡터와도연산이가능, 행렬이나벡터의모든원소들에스칼라를더하거나빼면됨 >> A=[1 2 3; 4 5 6]; >> B=[2 4 6; 1 3 5]; >> C=A+B C = 3 6 9 5 8 11 >> C-5 ans = -2 1 4 0 3 6
행렬의곱셈과나눗셈 행렬의곱셈 * 기호사용 두행렬또는벡터의내부차원 (inner dimension) 이일치해야함 행렬의나눗셈 스칼라와는달리일반적으로좌측나누기와우측나누기의결과가일치하지않음 좌측나누기 : X=A\B -----> A*X=B 의해 (X = inv(a)*b) >> X=A\B X = 0.2000 0.1000 0.6000 2.3000 >> inv(a)*b ans = 0.2000 0.1000 0.6000 2.3000
행렬의곱셈과나눗셈 우측나누기 : X=A/B ----> X*B=A 해 (X = A*inv(B)) >> X1=A/B X1 = 0.2500 0.2500-4.0000 6.0000 >> A*inv(B) ans = 0.2500 0.2500-4.0000 6.0000
행렬성분의연산 행렬의성분하나하나를각각연산하고싶을때 계산기호앞에. 을찍어주면된다. >> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >> A*A ans = 30 36 42 66 81 96 102 126 150 >> A.*A ans = 1 4 9 16 25 36 49 64 81
벡터 벡터의생성 시작값 : 증가분 : 최종값 형식으로지정 행벡터생성 시작값 : 최종값 형태로입력하면증가분은자동적으로 1 이됨 >> x=1:5 x = 1 2 3 4 5 >> y=0:0.5:3 y = 0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 >> z=5:-1:-5 z = 5 4 3 2 1 0-1 -2-3 -4-5 열벡터는행벡터로부터작은따옴표를사용하여생성
M-file When writing a program in MATLAB, save it as m-file ( filename.m) 2 types of M-file 1- script (has no input and output, simply execute commands) 2- function (need input, starts with keyword function ) function [y z]=mfunc(x) y=(x*x')^.5; % norm of x z=sum(x)/length(x); % using 'sum' function end
Polynomials Present polynomial with coefficients vector s 4 3s 3 2s 1 x = [1 3 0-2 1]; Poly converts roots to coefficients of a polynomial: ( s 2)( s 5)( s 6) P3=poly([-2-5 -6]) 2, 5, 6 roots=roots(p3) ( 2)( s 5) s P5=conv([1 2],[1 5])
Polynomials p=poly([-2 1 5]) R=roots(p) x=-3:0.1:6; y=p(1)*x.^3+p(2)*x.^2+p(3)*x+p(4); plot(x,y) grid 40 30 20 10 0 p = 1-4 -7 10-10 -20-30 R = 5.0000-2.0000 1.0000-40 -3-2 -1 0 1 2 3 4 5 6
Symbolic computation in MATLAB Syms s t %defines s and t as symbolic variable syms s a t G4=laplace(exp(t)) G4 =1/(s - 1) G5=laplace(exp(-t)) G5 =1/(s + 1) G6=laplace(sin(a*t)) G6 =a/(a^2 + s^2) ilaplace(f,s,t): computes Inverse Laplace transform of F on the complex variable s and returns it as a function of the time, t. ilaplace(a/(s^2+a^2),s,t)=(a*sin(t*(a^2)^(1/2)))/(a^2)^(1/2)
Symbolic computation in MATLAB A=[1,1;0,1]; syms t; Q=expm(A*t) %computes the matrix exponential of M. G=laplace(Q,t,s): G = [ 1/(s - 1), 1/(s - 1)^2] [ 0, 1/(s - 1)]
Control System Toolbox Tools to manipulate LTI models Classical analysis and design Bode, Nyquist, Nichols diagrams Step and impulse response Gain/phase margins Root locus design Modern state-space techniques Pole placement LQG regulation
Control System Toolbox LTI Objects (Linear Time Invariant) 4 basic types of LTI models Transfer Function (TF) Zero-pole-gain model (ZPK) State-Space models (SS) Frequency response data model (FRD) Conversion between models Model properties (dynamics)
Control System Toolbox Transfer Function H( s) p s p s... p q s q s q n n 1 1 2 n 1 m m 1... 1 1 m 1 where p, p... p numerator coefficients 1 2 n 1 q, q... q denominator coefficients 1 1 m 1
Control System Toolbox Transfer Function Consider a linear time invariant (LTI) singleinput/single-output system y'' 6 y' 5y 4 u' 3u Applying Laplace Transform to both sides with zero initial conditions Gs () Y( s) 4s 3 Us s s 2 () 6 5
Control System Toolbox Transfer Function >> num = [4 3]; >> den = [1 6 5]; >> sys = tf(num,den) Transfer function: 4 s + 3 ----------------- s^2 + 6 s + 5 >> [num,den] = tfdata(sys,'v') num = 0 4 3 den = 1 6 5
Control System Toolbox Zero-pole-gain model (ZPK) ( s p )( s p )... ( s p ) ( )( )... ( ) 1 2 n H ( s ) K s q 1 s q 2 s q m where p, p... p the zeros of H(s) 1 2 n 1 q, q... q the poles of H(s) 1 1 m 1
Control System Toolbox Zero-pole-gain model (ZPK) Consider a Linear time invariant (LTI) singleinput/single-output system y'' 6 y' 5y 4 u' 3u Applying Laplace Transform to both sides with zero initial conditions Gs () Y( s) 4s 3 4( s 0.75) U s s 6s 5 s s 2 ( ) ( 1)( 5)
Control System Toolbox Zero-pole-gain model (ZPK) >> sys1 = zpk(-0.75,[-1-5],4) Zero/pole/gain: 4 (s+0.75) ----------- (s+1) (s+5) >> [ze,po,k] = zpkdata(sys1,'v') ze = -0.7500 po = -1-5 k = 4
Control System Toolbox State-Space Model (SS). x A x B u y C x D u where x state vector u and y input and output vectors A, B, C and D state-space matrices
State-Space Models Consider a Linear time invariant (LTI) singleinput/single-output system y'' 6 y' 5y 4 u'' 3u State-space model for this system is x1' 0 1 x1 0 u x ' 5 6 x 1 2 2 x1 (0) 0 x2 (0) 0 y 3 4 x 1 x 2
Control System Toolbox >> sys = ss([0 1; -5-6],[0;1],[3,4],0) a = x1 x2 x1 0 1 x2-5 -6 b = u1 x1 0 x2 1 c = x1 x2 y1 3 4 d = u1 y1 0
Control System Toolbox State Space Models rss, drss - Random stable state-space models. ss2ss - State coordinate transformation. canon - State-space canonical forms. ctrb - Controllability matrix. obsv - Observability matrix. gram - Controllability and observability gramians. ssbal - Diagonal balancing of state-space realizations. balreal - Gramian-based input/output balancing. modred - Model state reduction. minreal - Minimal realization and pole/zero cancellation. sminreal - Structurally minimal realization.
Conversion between different models Transfer function tf2ss ss2tf State Space tf2zp zp2tf ss2zp zp2ss Zero-pole-gain
Model Dynamics pzmap: Pole-zero map of LTI models. pole, eig - System poles zero - System (transmission) zeros. dcgain: DC gain of LTI models. bandwidth - System bandwidth. iopzmap - Input/Output Pole-zero map. damp - Natural frequency and damping of system esort - Sort continuous poles by real part. dsort - Sort discrete poles by magnitude. covar - Covariance of response to white noise.
Time Response of Systems Impulse Response (impulse) Step Response (step) General Time Response (lsim) Polynomial multiplication (conv) Polynomial division (deconv) Partial Fraction Expansion (residue) gensig - Generate input signal for lsim.
Time Response of Systems The impulse response of a system is its output when the input is a unit impulse. The step response of a system is its output when the input is a unit step. The general response of a system to any input can be computed using the lsim command.
Control System Toolbox Problem Given the LTI system G(s) 2s 3 3s 2 4s 2 5s 1 Plot the following responses for: The impulse response using the impulse command. The step response using the step command. The response to the input both the lsim commands u(t ) sin(0.5t ) calculated using
Control System Toolbox Time Response of Systems
Frequency Domain Analysis and Design Root locus analysis Frequency response plots Bode Phase Margin Gain Margin Nyquist
Frequency Domain Analysis and Design Root Locus The root locus is a plot in the s-plane of all possible locations of the poles of a closed-loop system, as one parameter, usually the gain, is varied from 0 to. By examining that plot, the designer can make choices of values of the controller s parameters, and can infer the performance of the controlled closed-loop system.
Frequency Domain Analysis and Design Plot the root locus of the following system Root Locus Gs () Ks ( 8) s s s s 2 ( 2)( 8 32) >> rlocus(tf([1 8], conv(conv([1 0],[1 2]),[1 8 32])))
Frequency Response: Bode and Nyquist Plots Typically, the analysis and design of a control system requires an examination of its frequency response over a range of frequencies of interest. The MATLAB Control System Toolbox provides functions to generate two of the most common frequency response plots: Bode Plot (bode command) and Nyquist Plot (nyquist command).
Frequency Response: Bode Plot Problem Given the LTI system G(s ) 1 s(s 1) Draw the Bode diagram for 100 values of frequency in the interval 10 1 10.
Control System Toolbox >>bode(tf(1, [1 1 0]), logspace(-1,1,100));
Frequency Response: Nyquist Plot The loop gain Transfer function G(s) The gain margin is defined as the multiplicative amount that the magnitude of G(s) can be increased before the closed loop system goes unstable Phase margin is defined as the amount of additional phase lag that can be associated with G(s) before the closed-loop system goes unstable
Frequency Response: Nyquist Plot Problem Given the LTI system G(s) s 4 24.2s 3 1280s 640 1604.81s 2 320.24s 16 Draw the bode and nyquist plots for 100 values of 4 3 frequencies in the interval 10 10. In addition, find the gain and phase margins.
Frequency Response: Nyquist Plot w=logspace(-4,3,100); sys=tf([1280 640], [1 24.2 1604.81 320.24 16]); bode(sys,w) [Gm,Pm,Wcg,Wcp]=margin(sys) %Nyquist plot figure nyquist(sys,w)
Frequency Response: Nyquist Plot The values of gain and phase margin and corresponding frequencies are Gm = 29.8637 Pm = 72.8960 Wcg = 39.9099 Wcp = 0.9036
Control System Toolbox Frequency Response Plots bode - Bode diagrams of the frequency response. bodemag - Bode magnitude diagram only. sigma - Singular value frequency plot. Nyquist - Nyquist plot. nichols - Nichols plot. margin - Gain and phase margins. allmargin - All crossover frequencies and related gain/phase margins. freqresp - Frequency response over a frequency grid. evalfr - Evaluate frequency response at given frequency. interp - Interpolates frequency response data.
Control System Toolbox Design: Pole Placement place - MIMO pole placement. acker - SISO pole placement. estim - Form estimator given estimator gain. reg - Form regulator given state-feedback and estimator gains.
Control System Toolbox Design : LQR/LQG design lqr, dlqr - Linear-quadratic (LQ) state-feedback regulator. lqry - LQ regulator with output weighting. lqrd - Discrete LQ regulator for continuous plant. kalman - Kalman estimator. kalmd - Discrete Kalman estimator for continuous plant. lqgreg - Form LQG regulator given LQ gain and Kalman estimator. augstate - Augment output by appending states.
Control System Toolbox Analysis Tool: ltiview File->Import to import system from MATLAB workspace
Control System Toolbox Design Tool: sisotool Design with root locus, Bode, and Nichols plots of the open-loop system. Cannot handle continuous models with time delay.
M-File Example %Define the transfer function of a plant G=tf([4 3],[1 6 5]) %Get data from the transfer function [n,d]=tfdata(g,'v') [p,z,k]=zpkdata(g,'v') [a,b,c,d]=ssdata(g) %Check the controllability and observability of the system ro=rank(obsv(a,c)) rc=rank(ctrb(a,b)) %find the eigenvalues of the system damp(a) %multiply the transfer function with another transfer function T=series(G,zpk([-1],[-10-2j +2j],5)) %find the bandwidth of the new system wb=bandwidth(t) %plot the step response step(t) %plot the rootlocus rlocus(t) %obtain the bode plots bode(t) margin(t) %use the LTI viewer ltiview({'step';'bode';'nyquist'},t) %start the SISO tool sisotool(t) %plot the poles and zeros of the new system iopzmap(t)