Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 IntroductiontoMATLAB 國家太空計畫室 劉修任 October 21, 2004.

Similar presentations


Presentation on theme: "1 IntroductiontoMATLAB 國家太空計畫室 劉修任 October 21, 2004."— Presentation transcript:

1 1 IntroductiontoMATLAB 國家太空計畫室 劉修任 October 21, 2004

2 2 MATLAB Desktop

3 3  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 Running Functions and Entering Variables

4 4  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. Variable Types

5 5 Variable Types (Cont.)  Persistent Variables Characteristics of persistent variables are : 1.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 2.You can only use them in functions, other functions are not allowed access to them.

6 6 3.MATLAB does not clear them from memory when the function exits, so their value is retained from one function call to the next. 4.If you clear the function or edit the M-file for that function, then MATLAB clears all persistent variables used in that function. 5.If the persistent variable does not exist the first time you issue the PERSISTENT statement, it will be initialized to the empty matrix. Variable Types (Cont.)

7 7 Opening, Loading, Saving Files DirectiveDescriptionSyntax Importdata Load data from various types of files A = importdata('filename') load Load all or specific data from MAT or ASCII file 1.load filename 2.load('file.dat','-mat') 3.load(‘file.dat','-ascii') open Open files of various types using appropriate editor or program 1.Opening a file on the path: For example, to open the M-file, copyfile.m, type open copyfile.m 2.To open a file that is not on the MATLAB path, enter the complete file specification. For example open('D:\temp\data.mat') save Save all or specific data to MAT or ASCII file 1.To save all variables from the workspace in binary MAT-file. For example, test.mat, type save test.mat 2.To save variables p and q in binary MAT-file. For example, test.mat, type savefile = 'test.mat'; p = rand(1,10); q = ones(10); save(savefile,'p','q') 3.To save the variables vol and temp in ASCII format to a file named june10, type save('d:\mymfiles\june10','vol','temp','-ASCII') winopen Open file in appropriate application (Windows only) Open the file “thesis.doc”, located in the current directory, in Microsoft Word. For example, winopen('thesis.doc')

8 8 Low-Level File I/O DirectiveDescriptionSyntax fcloseClose one or more open filesstatus = fclose(fid) status = fclose('all') feofTest for end-of-fileeofstat = feof(fid) ferrorQuery MATLAB about errors in file input or outputmessage = ferror(fid) fgetlReturn next line of file as string without line terminator(s)tline = fgetl(fid) fgetsReturn next line of file as string with line terminator(s)tline = fgets(fid) fopenOpen file or obtain information about open filesfid = fopen(filename) fprintfWrite formatted data to filecount = fprintf(fid,format,A,...) freadRead binary data from file[A,count] = fread(fid,size,precision) [A,count] = fread(fid,size,precision,skip) frewindRewind open filefrewind(fid) fscanfRead formatted data from fileA = fscanf(fid,format) [A,count] = fscanf(fid,format,size) fseekSet file position indicatorstatus = fseek(fid,offset,origin) ftellGet file position indicatorposition = ftell(fid) fwriteWrite binary data to filecount = fwrite(fid,A,precision) count = fwrite(fid,A,precision,skip)

9 9 Arithmetic Operators SymbolicM-file Function Matrix multiplicationA*Bmtimes(A,B) Array-wise multiplicationA.*Btimes(A,B) Matrix right divisionA/Bmrdivide(A,B) ( A*INV(B) ) Array-wise right divisionA./Brdivide(A,B) Matrix left divisionA\Bmldivide(A,B) ( INV(A)*B ) Array-wise left divisionA.\Bldivide(A,B) Matrix power A^B (both A and B are matrices, is an error) mpower(A,B) Array-wise powerA.^Bpower(A,B) Complex transposeA‘ctranspose(A) Matrix transposeA.‘transpose(A) Example:

10 10  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 % Comment lines % "flower petal" plots 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 Scripts

11 11 Scripts (Cont.)  Results for the script executed: : After the script displays a plot, press “Enter” to move to the next plot. Figure A  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 B

12 12  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 Function

13 13  Entering these commands in an M-file called average.m.  To call the average function, enter z = 1:99 average(z) ans = 50 Function (Cont.)

14 14 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 elseif 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 value1 statements % Executes if expression is value1 case value2 statements % Executes if expression is value2.. 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 Flow Control

15 15 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.return causes execution to return to the invoking function. For example: try X = A * B catch disp '** Error multiplying A * B' end

16 16 Basic Plotting Commands  plot: Graph 2-D data with linear scales for both axes  plot3: Graph 3-D data with linear scales for both axesloglogGraph with logarithmic scales for both axes  semilogx: Graph with a logarithmic scale for the x-axis and a linear scale for the y- axis  semilogy: Graph with a logarithmic scale for the y-axis and a linear scale for the x- axis  plotyy: Graph with y-tick labels on the left and right side For example: x = 0:0.01:20; y1 = 200*exp(-0.05*x).*sin(x); y2 = 0.8*exp(-0.5*x).*sin(10*x); [AX,H1,H2] = plotyy(x,y1,x,y2,'plot');

17 17 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 = ss(a,b,c,d) For example: 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 = tf(num,den) For example: sys_tf = tf(1.5,[1 14 40.02])

18 18 Building Models 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. sys1 = tf(num,den,Ts) sys2 = zpk(z,p,k,Ts) sys3 = ss(a,b,c,d,Ts) Building Models (Cont.)

19 19 Interconnecting Linear Models  Series connection of two LTI (Linear Time-Invariant) models: sys = series(sys1,sys2)  Parallel connection of two LTI models: sys = parallel(sys1,sys2)  Feedback connection of two LTI models: sys = feedback(sys1,sys2,-1) sys1sys2 sys uy sys1 sys2 sys u y + + sys1 sys2 uy - +

20 20 Common Control Functions  Model Dynamics  Time Responses DirectiveDescriptionSyntax bandwidthCompute the frequency response bandwidthfb = bandwidth(sys) dampCompute damping factors and natural frequencies[Wn,Z,P] = damp(sys) poleCompute the poles of an LTI systemp = pole(sys) eigFind eigenvalues and eigenvectors[V,D] = eig(A) rlocusEvans root locusrlocus(sys) rootsPolynomial rootsr = roots(c) DirectiveDescriptionSyntax impulseCompute the impulse response of LTI modelsimpulse(sys) impulse(sys,t) initialCompute the initial condition response of state-space modelsinitial(sys,x0) initial(sys,x0,t) stepStep response of LTI systemsstep(sys) step(sys,t)

21 21 Common Control Functions (Cont.)  Frequency Response DirectiveDescriptionSyntax bodeCompute the Bode frequency response of LTI models[mag,phase,w] = bode(sys) marginCompute gain and phase margins and associated crossover frequencies [Gm,Pm,Wcg,Wcp] = margin(sys) nicholsCompute Nichols frequency response of LTI modelsnichols(sys) nyquistCompute Nyquist frequency response of LTI modelsnyquist(sys)

22 22 Starting Simulink Click the Simulink icon on the MATLAB toolbar, or enter the simulink command at the MATLAB prompt

23 23 Creating a New Model

24 24 Creating a New Model (Cont.)

25 25 Connecting Blocks & Their Parameters Setting

26 26 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.

27 27 To model the differential equation where u(t) is a square wave with an amplitude of 1 and a frequency of 1 rad/sec. Modeling a Simple Continuous System P.S. Click the Start simulation icon on the MATLAB toolbar, or enter the sim(‘example_1’) command at the MATLAB prompt Start simulation icon

28 28 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.

29 29 Simple S/C Control Example

30 30 控制器 (Controller) 致動器 (Actuators) 衛星動態 & 衛星軌道 感測器 (Sensors) 估測器 (Estimator) 濾波器 (Compensator) 1. 衛星姿態 (Quaternion) 2. 衛星角速度 (Angular Velocity) 1. 命令 : 衛星姿態 2. 命令 : 衛星角速度 3. 命令 : 衛星角加速度 1. 迴授訊號 : 衛星姿態 2. 迴授訊號 : 衛星角速度 General Structure of a Satellite Attitude Determination and Control Subsystem Implemented by Software ADCS Hardware 太空環境 (Environment) Disturbance Simple S/C Control Example (Cont.) -- Attitude Control Block Diagrm

31 31 Dynamic Equation –I: Spacecraft moment of inertia –N: External torque (Thruster & Environment) –H w : Wheel angular momentum –w: Spacecraft angular velocity Kinematical Equation –Q: Spacecraft quaternion Simple S/C Control Example (Cont.) -- Dynamic & Kinematic Equations

32 32 Simple S/C Control Example (Cont.) -- Block: Dynamic & Kinematic Eq.

33 33 Simple S/C Control Example (Cont.) -- Block: PD Controller & Timer

34 34 Simple S/C Control Example (Cont.) -- Block: Data Display

35 35 Simple S/C Control Example (Cont.) -- Simulation Results

36 36 MATLAB -- Help

37 37 Homework I + - r y 1.Plot the root locus using MATLAB for the open-loop system shown in the figure with, and. 2.If K = 3.7, plot the step response.

38 38 Homework II M B K f(t) x(t) 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 = 1kg, friction coefficient B = 5N/m/sec., and the spring constant K = 25 N/m. Plot the time response of the displacement and velocity of the system.


Download ppt "1 IntroductiontoMATLAB 國家太空計畫室 劉修任 October 21, 2004."

Similar presentations


Ads by Google