Introduction to MATLAB October 21 2004 1 MATLAB
Introduction to MATLAB 國家太空計畫室 劉修任 October 21, 2004 1
MATLAB Desktop 2
Running Functions and Entering Variables Ø The prompt (>>) in the Command Window indicates that MATLAB is ready to accept input from you. Ø To enter a variable, type the variable with its assignment. For example, type A = [1 2 3; 4 5 6; 7 8 10] , then MATLAB responds with A= 1 2 3 4 5 6 7 8 10 Ø To run a function, type the function including all arguments. For example, type magic(2), then MATLAB returns ans = 1 3 4 2 3
Variable Types Ø Local Variables Each MATLAB function has its own local variables. These are separate from those of other functions, and from those of the base workspace. Variables defined in a function do not remain in memory from one function call to the next, unless they are defined as global or persistent. Ø Global Variables If several functions, all declare a particular name as global, then they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the other functions declaring it global. 4
Variable Types (Cont. ) Ø Persistent Variables Characteristics of persistent variables are : 1. 2. They differ from global variables in that persistent variables are known only to the function in which they are declared. This prevents persistent variables from being changed by other functions or from the MATLAB command line You can only use them in functions, other functions are not allowed access to them. 5
Variable Types (Cont. ) 3. 4. 5. MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next. If you clear the function or edit the M-file for that function, then MATLAB clears all persistent variables used in that function. If the persistent variable does not exist the first time you issue the PERSISTENT statement, it will be initialized to the empty matrix. 6
Opening, Loading, Saving Files Directive Description Importdata Load data from various types of files A = importdata('filename') load Load all or specific data from MAT or ASCII file 1. 2. 3. load filename load('file. dat', '-mat') load(‘file. dat', '-ascii') 1. Opening a file on the path: For example, to open the M-file, copyfile. m, type open Open files of various types using appropriate editor or program Syntax open copyfile. m 2. To open a file that is not on the MATLAB path, enter the complete file specification. For example open('D: tempdata. mat') 1. To save all variables from the workspace in binary MAT-file. For example, test. mat, type save test. mat 2. save Save all or specific data to MAT or ASCII file savefile = 'test. mat'; p = rand(1, 10); q = ones(10); save(savefile, 'p', 'q') 3. winopen Open file in appropriate application (Windows only) To save variables p and q in binary MAT-file. For example, test. mat, type To save the variables vol and temp in ASCII format to a file named june 10, type save('d: mymfilesjune 10', 'vol', 'temp', '-ASCII') Open the file “thesis. doc”, located in the current directory, in Microsoft Word. For example, winopen('thesis. doc') 7
Low-Level File I/O Directive fclose Description Syntax Close one or more open files status = fclose(fid) status = fclose('all') Test for end-of-file eofstat = feof(fid) Query MATLAB about errors in file input or output message = ferror(fid) fgetl Return next line of file as string without line terminator(s) tline = fgetl(fid) fgets Return next line of file as string with line terminator(s) tline = fgets(fid) fopen Open file or obtain information about open files fid = fopen(filename) fprintf Write formatted data to file count = fprintf(fid, format, A, . . . ) fread Read binary data from file [A, count] = fread(fid, size, precision) [A, count] = fread(fid, size, precision, skip) Rewind open file frewind(fid) fscanf Read formatted data from file A = fscanf(fid, format) [A, count] = fscanf(fid, format, size) fseek Set file position indicator status = fseek(fid, offset, origin) ftell Get file position indicator position = ftell(fid) Write binary data to file count = fwrite(fid, A, precision) count = fwrite(fid, A, precision, skip) feof ferror frewind fwrite 8
Arithmetic Operators Symbolic M-file Function Matrix multiplication A*B mtimes(A, B) Array-wise multiplication A. *B times(A, B) Matrix right division A/B mrdivide(A, B) ( A*INV(B) ) Array-wise right division A. /B rdivide(A, B) Matrix left division AB mldivide(A, B) ( INV(A)*B ) Array-wise left division A. B ldivide(A, B) Matrix power A^B (both A and B are matrices, is an error) mpower(A, B) Array-wise power A. ^B power(A, B) Complex transpose A‘ ctranspose(A) Matrix transpose A. ‘ transpose(A) Example: 9
Scripts Ø Simple Script Example These statements calculate rho for several trigonometric functions of theta, then create a series of polar plots. % An M-file script to produce % "flower petal" plots % Comment lines theta = -pi: 0. 01: pi; % Computations rho(1, : ) = 2*sin(5*theta). ^2; rho(2, : ) = cos(10*theta). ^3; rho(3, : ) = sin(theta). ^2; rho(4, : ) = 5*cos(3. 5*theta). ^3; for k = 1: 4 polar(theta, rho(k, : )) % Graphics output pause end 10
Scripts (Cont. ) Ø Entering the commands in an M-file called petals. m (shown as Figure A). Typing petals at the MATLAB command line executes the statements in the script (shown as Figure B). Figure A Figure B Ø Results for the script executed: : After the script displays a plot, press “Enter” to move to the next plot. 11
Function Ø Simple Function Example The average function is a simple M-file that calculates the average of the elements in a vector. function y = average(x) % AVERAGE Mean of vector elements. % AVERAGE(X), where X is a vector, is the mean of vector elements. % Nonvector input results in an error. [m, n] = size(x); if (~((m == 1) | (n == 1)) | (m == 1 & n == 1)) error('Input must be a vector') end y = sum(x)/length(x); % Actual computation 12
Function (Cont. ) Ø Entering these commands in an M-file called average. m. Ø To call the average function, enter z = 1: 99 average(z) ans = 50 13
Flow Control There are eight flow control statements in MATLAB: 1. if, together with else and elseif …end, executes a group of statements based on some logical condition. if logical_expression statements else statements end 1. switch, together with case and otherwise, executes different groups of statements depending on the value of some logical condition. switch expression (scalar or string) case value 1 statements % Executes if expression is value 1 case value 2 statements % Executes if expression is value 2. . otherwise statements % Executes if expression does not match any case end 1. while executes a group of statements an indefinite number of times, based on some logical condition. while expression statements end 14
Flow Control (Cont. ) 4. for executes a group of statements a fixed number of times. for index = start: increment: end statements end 5. continue passes control to the next iteration of a for or while loop, skipping any remaining statements in the body of the loop. 6. break terminates execution of a for or while loop. 7. try. . . catch…end changes flow control if an error is detected during execution. try, statement, . . . , statement, catch, statement, . . . , statement, end 8. For example: try X = A * B catch disp '** Error multiplying A * B' end return causes execution to return to the invoking function. 15
Basic Plotting Commands Ø plot: Graph 2 -D data with linear scales for both axes Ø plot 3: Graph 3 -D data with linear scales for both axesloglog. Graph with logarithmic scales for both axes Ø semilogx: Graph with a logarithmic scale for the x-axis and a linear scale for the yaxis Ø semilogy: Graph with a logarithmic scale for the y-axis and a linear scale for the xaxis Ø plotyy: Graph with y-tick labels on the left and right side For example: x = 0: 0. 01: 20; y 1 = 200*exp(-0. 05*x). *sin(x); y 2 = 0. 8*exp(-0. 5*x). *sin(10*x); [AX, H 1, H 2] = plotyy(x, y 1, x, y 2, 'plot'); 16
Building Models Ø Linear Models--Building single-input, single-output (SISO) models of linear time-invariant (LTI) dynamical systems, including state-space, pole/zero, and transfer functions. a. State-space (SS) models: sys_ss For example: = ss(a, b, c, d) A = [1 0; 0 1]; B = [1; 0]; C = [0 1]; D = [0]; sys_ss = ss(A, B, C, D) b. Transfer functions (TF) model: sys_tf For example: = tf(num, den) sys_tf = tf(1. 5, [1 14 40. 02]) 17
Building Models (Cont. ) c. Zero-pole-gain (ZPK) model: sys_zpk = zpk(z, p, k) For example: sys_zpk = zpk([], [-9. 996 -4. 004], 1. 5) Ø Discrete-Time Models-- Creating discrete-time models is very much like creating continuous-time models, except that you must also specify a sampling period or sample time for discrete-time models. sys 1 = tf(num, den, Ts) sys 2 = zpk(z, p, k, Ts) sys 3 = ss(a, b, c, d, Ts) 18
Interconnecting Linear Models Ø Series connection of two LTI (Linear Time-Invariant) models: sys = series(sys 1, sys 2) sys u Ø sys 1 sys 2 Parallel connection of two LTI models: sys = parallel(sys 1, sys 2) sys 1 sys + y u sys 2 Ø y + Feedback connection of two LTI models: sys = feedback(sys 1, sys 2, -1) u + sys 1 y sys 2 19
Common Control Functions Ø Model Dynamics Directive bandwidth Description Syntax Compute the frequency response bandwidth fb = bandwidth(sys) Compute damping factors and natural frequencies [Wn, Z, P] = damp(sys) pole Compute the poles of an LTI system p = pole(sys) eig Find eigenvalues and eigenvectors [V, D] = eig(A) rlocus Evans root locus rlocus(sys) roots Polynomial roots r = roots(c) damp Ø Time Responses Directive impulse initial step Description Syntax Compute the impulse response of LTI models impulse(sys) impulse(sys, t) Compute the initial condition response of state-space models initial(sys, x 0) initial(sys, x 0, t) Step response of LTI systems step(sys) step(sys, t) 20
Common Control Functions (Cont. ) Ø Frequency Response Directive bode Description Syntax Compute the Bode frequency response of LTI models [mag, phase, w] = bode(sys) margin Compute gain and phase margins and associated crossover frequencies [Gm, Pm, Wcg, Wcp] = margin(sys) nichols Compute Nichols frequency response of LTI models nichols(sys) nyquist Compute Nyquist frequency response of LTI models nyquist(sys) 21
Starting Simulink Click the Simulink icon on the MATLAB toolbar, or enter the simulink command at the MATLAB prompt 22
Creating a New Model 23
Creating a New Model (Cont. ) 24
Connecting Blocks & Their Parameters Setting 25
Running a Simulation Running a Simulink model is generally a two-step process: 1. Specify various simulation parameters (either on the Simulation Parameters dialog box, from the model editor's Simulation menu or using simset or set_param commands. 2. Start the simulation To start execution of a model, select Start from the model editor's Simulation menu or click the Start button on the model's toolbar. You can also use the keyboard shortcut, Ctrl+T, to start the simulation. 26
Modeling a Simple Continuous System To model the differential equation where u(t) is a square wave with an amplitude of 1 and a frequency of 1 rad/sec. Start simulation icon P. S. Click the Start simulation icon on the MATLAB toolbar, or enter the sim(‘example_1’) command at the MATLAB prompt 27
Modeling a Second-Order Control System To model a second-order plant and the controller into a closed-loop system, and then to simulate its step response. 28
Simple S/C Control Example 29
Simple S/C Control Example (Cont. ) -- Attitude Control Block Diagrm Implemented by Software 1. 命令: 衛星姿態 2. 命令: 衛星角速度 3. 命令: 衛星角加速度 ADCS Hardware 太空環境 (Environment) Disturbance 控制器 (Controller) 濾波器 (Compensator) 估測器 (Estimator) 致動器 (Actuators) 衛星動態 & 衛星軌道 1. 衛星姿態 (Quaternion) 2. 衛星角速度 (Angular Velocity) 感測器 (Sensors) 1. 迴授訊號: 衛星姿態 2. 迴授訊號: 衛星角速度 General Structure of a Satellite Attitude Determination and Control Subsystem 30
Simple S/C Control Example (Cont. ) -- Dynamic & Kinematic Equations • Dynamic Equation – – I: Spacecraft moment of inertia N: External torque (Thruster & Environment) Hw: Wheel angular momentum w: Spacecraft angular velocity • Kinematical Equation – Q: Spacecraft quaternion 31
Simple S/C Control Example (Cont. ) -- Block: Dynamic & Kinematic Eq. 32
Simple S/C Control Example (Cont. ) -- Block: PD Controller & Timer 33
Simple S/C Control Example (Cont. ) -- Block: Data Display 34
Simple S/C Control Example (Cont. ) -- Simulation Results 35
MATLAB -- Help 36
Homework I r y + - 1. Plot the root locus using MATLAB for the open-loop system shown in the figure with , 2. and . If K = 3. 7, plot the step response. 37
Homework II Consider the simple mechanical system of the figure. Three forces influence the motion of the mass, namely, the applied force, the frictional force, and spring force. Applying Newton’s low of motion, the force equation of the system is With the system initially at rest, a force of 25 Newton is applied at time t = 0. Assume that the mass M = 1 kg, friction coefficient B = 5 N/m/sec. , and the spring constant K = 25 N/m. Plot the time response of the displacement and velocity of the system. K B M x(t ) f(t) 38
- Slides: 38