introduction to matlab 國家太空計畫室 劉修任 october 21, 2004

38
1 Introduction Introduction to to MATLAB MATLAB 國國國國國國國 國國國 October 21, 2004

Upload: holly-gilbert

Post on 02-Jan-2016

68 views

Category:

Documents


0 download

DESCRIPTION

Introduction to MATLAB 國家太空計畫室 劉修任 October 21, 2004. MATLAB Desktop. Running Functions and Entering Variables. The prompt (>>) in the Command Window indicates that MATLAB is ready to accept input from you. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

1

Introduction Introduction

to to MATLABMATLAB

國家太空計畫室劉修任

October 21, 2004

Page 2: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

2

MATLAB Desktop

Page 3: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 4: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

4

Local VariablesEach 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 VariablesIf 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

Page 5: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

5

Variable Types (Cont.)

Persistent VariablesCharacteristics 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.

Page 6: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 7: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

7

Opening, Loading, Saving Files

Directive Description Syntax

ImportdataLoad data from various types of files

A = importdata('filename')

loadLoad all or specific data from MAT or ASCII file

1. load filename

2. load('file.dat','-mat')

3. load(‘file.dat','-ascii')

openOpen 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')

saveSave 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')

winopenOpen file in appropriate application (Windows only)

Open the file “thesis.doc”, located in the current directory, in Microsoft Word. For example,

winopen('thesis.doc')

Page 8: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

8

Low-Level File I/O

Directive Description Syntax

fclose Close one or more open files status = fclose(fid)

status = fclose('all')

feof Test for end-of-file eofstat = feof(fid)

ferror 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)

frewind 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)

fwrite Write binary data to file count = fwrite(fid,A,precision)

count = fwrite(fid,A,precision,skip)

Page 9: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

9

Arithmetic Operators

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 A\B mldivide(A,B) ( INV(A)*B )

Array-wise left division A.\B ldivide(A,B)

Matrix powerA^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:

86

42,

43

21BA

4430

2014),(* BAmtimesBA

3218

82),(*. BAtimesBA

Page 10: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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; % Computationsrho(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 pauseend

Scripts

Page 11: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 12: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 13: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 14: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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 statementselseif logical_expression statementselse statementsend

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 caseend

1. while executes a group of statements an indefinite number of times, based on some logical condition.

while expression statementsend

Flow Control

Page 15: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

15

Flow Control (Cont.)

4. for executes a group of statements a fixed number of times.

for index = start:increment:end statementsend

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 * Bcatch disp '** Error multiplying A * B'end

Page 16: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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');

Page 17: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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])

Page 18: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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 yo

u 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.)

Page 19: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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)

sys1 sys2

sys

u y

sys1

sys2

sys

u y+

+

sys1

sys2

u y

-

+

Page 20: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

20

Common Control Functions

Model Dynamics

Time Responses

Directive Description Syntax

bandwidth Compute the frequency response bandwidth fb = bandwidth(sys)

damp 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)

Directive Description Syntax

impulse Compute the impulse response of LTI models impulse(sys)

impulse(sys,t)

initial Compute the initial condition response of state-space models initial(sys,x0)

initial(sys,x0,t)

step Step response of LTI systems step(sys)

step(sys,t)

Page 21: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

21

Common Control Functions (Cont.)

Frequency Response

Directive Description Syntax

bode 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)

Page 22: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

22

Starting Simulink

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

Page 23: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

23

Creating a New Model

Page 24: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

24

Creating a New Model (Cont.)

Page 25: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

25

Connecting Blocks & Their Parameters Setting

Page 26: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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 th

e model editor's Simulation menu or using simset or set_param commands.

2. Start the simulationTo 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.

Page 27: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

)()(2)(' tutxtx

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

Page 28: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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.

ss 2

92

K

Page 29: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

29

Simple S/C Control Example

Page 30: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

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

Page 31: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

31

• 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

)( ww HIww

dt

dHN

dt

dwI

4

3

2

1

4321

0

0

0

0

2

1

2

1

q

q

q

q

www

www

www

www

Q

qqqqQ

QwQ

zyx

zxy

yxz

xyz

T

Simple S/C Control Example (Cont.)-- Dynamic & Kinematic Equations

Page 32: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

32

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

Page 33: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

33

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

Page 34: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

34

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

Page 35: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

35

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

Page 36: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

36

MATLAB -- Help

Page 37: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

37

Homework I

)(sG)(sD

)(sH

+

-

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.

10

3)(

s

sKsD

)2(

10)(

sssG 1)( sH

Page 38: Introduction  to  MATLAB 國家太空計畫室 劉修任 October 21, 2004

38

Homework II

M

BK

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.

)(2

2

tfKxdt

dxB

dt

xdM