Vous êtes sur la page 1sur 53

Introduction to Matlab

Prof. Dr. Y. Samim nlsoy

Prof. Dr. Y. Samim NLSOY Mech. Eng. Dept., Middle ME 513 Vehicle Dynamics East Technical 1 University, Ankara

MATLAB 7.0.1.lnk

MATLAB
Load or save files here

Double-click

stored values here


Watch your

Write your commands here

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

INTRODUCTION TO MATLAB
Matrices In MATLAB, a matrix is a rectangular array of numbers.
Scalars are 1-by-1 matrices. Vectors are matrices with only one row or column.

MATLAB has other ways of storing both numeric and nonnumeric data; but in the beginning, it is usually best to think of everything as a matrix. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 3

HOW TO ENTER MATRICES


You can enter matrices into MATLAB in several different ways:
Enter an explicit list of elements. Load matrices from external data files. Generate matrices using built-in functions. Create matrices with your own functions in M-files.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

Entering a Matrix
You have only to follow a few basic conventions:
Separate the elements of a row with blanks or commas. Use a semicolon, ; ,to indicate the end of each row. Surround the entire list of elements with square brackets, [ ].

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

Entering A Matrix
Start by entering the matrix as a list of its elements. To enter, simply type in the Command Window
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can refer to it simply as A. Now that you have A in the workspace.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

MatLab Command Window


>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A= 16 3 5 10 9 6 4 15 >>
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 7

2 13 11 8 7 12 14 1

Transpose of a Matrix
There are two possibilities to transpose a matrix. Use an apostrophe or single quote, '.

Type transpose(A), where A is the matrix transpose of which is sought.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

A= 16 3 5 10 9 6 4 15 2 13 11 8 7 12 14 1

MatLab Command Window

>> A' ans = 16 5 3 10 2 11 13 8 9 4 6 15 7 14 12 1

>> transpose(A) ans = 16 5 3 10 2 11 13 8 >>


Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 9

9 4 6 15 7 14 12 1

Inverse of a Matrix
inv(X) is the inverse of the square matrix X.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

10

C= 16 3 5 10 9 6 4 15 2 13 11 8 15 12 14 1

>> C C= 16 3 2 13 5 10 11 8 9 6 15 12 4 15 14 1 >> B=inv(C) C= 0.0760 -0.1985 0.0417 0.1005 0.0196 0.1544 -0.1250 0.0098 -0.0417 -0.1250 0.1250 0.0417 -0.0147 0.2279 -0.0417 -0.1324 >>

MatLab Command Window

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

11

Subscripts
The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. So it is possible to compute the sum of the elements in the fourth column of A by typing
A(1,4) + A(2,4) + A(3,4) + A(4,4)

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

12

The expression 1:10 is a row vector containing the integers from 1 to 10 1 2 3 4 5 6 7 8 9 10 To obtain nonunit spacing, specify an increment. 100:-7:50 is 100 93 86 79 72 65 58 51 and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.1416

Colon Operator

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

13

>> 1:10 ans = 1 2 3 4 5 6 7 8 9 10

>> 100:-7:50 ans = 100 93 86 79 72 65 58 51

MatLab Command Window

>> 0:pi/4:pi ans = 0 >>


Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 14

0.7854

1.5708

2.3562

3.1416

Colon Operator
Subscript expressions involving colons refer to portions of a matrix. A(1:k,j) is the first k elements of the jth column of A. So sum(A(1:4,4)) computes the sum of the fourth column. The colon by itself refers to all the elements in a row or column of a matrix and end refers to the last row or column. So sum(A(:,end)) computes the sum of the elements in the last column of A.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 15

A= 16 3 5 10 9 6 4 15 2 13 11 8 7 12 14 1

>> sum(A(1:4,4)) ans = 34 >> sum(A(:,end)) ans = 34 >>

MatLab Command Window

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

16

Matrix Multiplication and Division


C = A*B is the linear algebraic product of the matrices A and B. For nonscalar A and B, the number of columns of A must equal the number of rows of B. A scalar can multiply a matrix of any size. .* Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 17

A= 16 3 5 10 B= 7 12 14 1

>> A*B ans = 154 195 175 70 >> A.*B ans = 112 36 70 10 >>

MatLab Command Window


16*7+3*14=154 16*12+3*1=195 5*7+10*14=175 5*12+10*1=70

16*7=112 3*12=36 5*14=70 10*1=10

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

18

Matrix Multiplication and Division


/ matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A'\B')'. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. \ matrix left division. If A is a square matrix, A\B is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\B is the solution to the equation AX = B computed by Gaussian elimination.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

19

A= 16 3 5 10 B= 7 12 14 1

>> B/A ans = 0.0690 1.1793 0.9310 -0.1793 >> B*inv(A) ans = 0.0690 1.1793 0.9310 -0.1793 >>

MatLab Command Window

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

20

A= 16 3 5 10 B= 7 12 14 1

>> A./B ans = 2.2857 0.2500 0.3571 10.0000 >> A\B ans = 0.1931 0.8069 1.3034 -0.3034 >>

MatLab Command Window


>> inv(A)*B ans = 0.1931 0.8069 1.3034 -0.3034 >>

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

21

Eigenvalues and Eigenvectors


E = eig(X) is a vector containing the eigenvalues of a square matrix X. [V,D] = eig(X) produces a diagonal matrix D of eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that X*V = V*D.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 22

A= 16 3 5 10 9 6 4 15 2 13 11 8 15 12 14 1

MatLab Command Window

>> A A= 16 3 2 13 5 10 11 8 9 6 15 12 4 15 14 1 >> G=eig(A) G= 36.3739 -7.1081 8.0000 4.7341 >>

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

23

Eigenvalues and Eigenvectors


E = eig(A,B) is a vector containing the generalized eigenvalues of square matrices A and B. [V,D] = eig(A,B) produces a diagonal matrix D of generalized eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that A*V = B*V*D.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 24

Variables
MATLAB does not require any type declarations or dimension statements. A new variable name is automatically created and appropriate amount of storage is allocated. If the variable already exists, MATLAB changes its contents and, if necessary, allocates new storage. Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB uses only the first 31 characters of a variable name. MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the same variable. To view the matrix assigned to any variable, simply enter the variable name and press enter.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

25

Functions
MATLAB provides a large number of standard elementary mathematical functions, such as
abs, sqrt, exp, and sin, cos, tan etc..

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

26

Advanced Mathematical Functions


Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically. MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

27

Help on Available Functions


For a list of the elementary mathematical functions, type help elfun For a list of more advanced mathematical and matrix functions, type help specfun help elmat

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

28

Built-in and m-file Functions


Some of the functions, like sqrt and sin, are built-in. They are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in m-files. You can see the code and even modify it if you want.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

29

PLOTS >>help plot


PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up. If X is a scalar and Y is a vector, length(Y) disconnected points are plotted. PLOT(Y) plots the columns of Y versus their index. If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)). In all other uses of PLOT, the imaginary part is ignored.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

30

PLOTS >>help plot


Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns: b g r c m y k blue . point green o circle red x x-mark cyan + plus magenta * star yellow s square black d diamond solid : dotted -. dashdot -- dashed

For example, PLOT(X,Y,'c+:') plots a cyan dotted line with a plus at each data point; PLOT(X,Y,'bd') plots blue diamond at each data point but does not draw any line.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

31

PLOTS >> help plot


PLOT(X1,Y1,S1,X2,Y2,S2,X3,Y3,S3,...) combines the plots defined by the (X,Y,S) triples, where the X's and Y's are vectors or matrices and the S's are strings. For example, PLOT(X,Y,'y-',X,Y,'go') plots the data twice, with a solid yellow line interpolating green circles at the data points. The PLOT command, if no color is specified, makes automatic use of the colors specified by the axes ColorOrder property. The default ColorOrder is listed in the table above for color systems where the default is blue for one line, and for multiple lines, to cycle through the first six colors in the table. For monochrome systems, PLOT cycles over the axes LineStyleOrder property. See also SEMILOGX, SEMILOGY, LOGLOG, PLOTYY, GRID, CLF, CLC, TITLE, XLABEL, YLABEL, AXIS, AXES, HOLD, COLORDEF, LEGEND, SUBPLOT, STEM.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

32

Solution of Linear Ordinary Differential Equations with Constant Coefficients


>> help tf tf : Creation of transfer functions or conversion to transfer function.

sys = tf(num, den)


creates a continuous-time transfer function sys with numerator num and denominator den. The output sys is a tf object. s = tf('s') specifies the transfer function H(s) = s (Laplace variable). You can then specify transfer functions directly as rational expressions in s, e.g., s = tf('s'); H = (s+1)/(s^2+3*s+1)
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 33

Time Response for LTI Systems : lsim


Matlab command lsim (sys, u, t) is used to simulate time response of LTI models to arbitrary inputs described by u. The time vector t consists of regularly spaced time samples and u is a matrix with as many columns as inputs and whose i-th row specifies the input value at time t(i). For example, t = 0:0.01:5; u = sin(t); lsim(sys,u,t) simulates the response of a single-input model sys to the input u(t)=sin(t) for 5 seconds by 0.01 second intervals.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 34

m-files
There are two types of m-files :

Script m-files, and Function m-Files


M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept arguments and produce output. You create M-files using a text editor, then use them as you would any other MATLAB function or command.
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 35

m-files
Script M-Files
Do not accept input arguments or return output arguments. Operate on data in the workspace. Useful for automating a series of steps you need to perform many times.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

36

Script M-Files
Consider a one degree of freedom mass-spring-damper system representing a road vehicle travelling on a rough road surface. x m c k z Obtain the motion of the vehicle in terms of the vehicle body mass displacement y and its derivatives. Assume that the road surface profile z is sinusoidal with a frequency of 5 rad/s and an amplitude of 1 cm.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

37

x m c k z

Script M-Files
The equation of motion is given as :

mx + cx + kx = cz + kz
The transfer function is then given by :

X(s) cs + k G(s) = = Z(s) ms2 + cs + k

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

38

% March 2004 % Response of a vehicle travelling on a % sinusoidal road surface profile. % ------------------------------------------------% Define Parameters and Variables % m : vehicle mass [kg]

Script M-Files

% c : total damping coefficient of suspension dampers [m/s] % k : total spring constant of suspension springs [kN/m] % z : vehicle body displacement [m] % ------------------------------------------------% Enter Data Values m=1260; c=4000; k=60000; .....

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

39

.....

Script M-Files

% --------------------------------------------------------% Generate the time array for the solution t=0:0.01:10; % time array (from 0 to 10 seconds with 0.01 second increments) % ----------------------------------------------% Generate the road surface profile A=0.01; % road surface profile amplitude [m] omega=5; % road surface profile frequency [rad/s] z=A*sin(omega*t); % road surface profile [m] % ---------------------------------------% Plot the road surface profile
figure(1) plot(t,z) title(Sinusoidal Road Surface Profile - Amplitude : 1 cm, Frequency : 5 rad/s); xlabel(Time[s]);ylabel(y[m]);

.....

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

40

.....

Script M-Files

% ------------------------------------------% Generate the transfer functions s=tf(s); % Declare s as the Laplace variable % from z to y hz=(c*s+k)/(m*s^2+c*s+k); % from z to ydot (velocity) hzdot=s*hz; % from z to ydoubledot (acceleration) hzddot=s*hzdot; % ----------------------------------------------% Plot the displacement, velocity, and acceleration of % the vehicle body figure(2) % Plot of displacement note that hz is the TF from z to y lsim(hz,z,t) .....
Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 41

Script M-Files
..... figure(3) % Plot of velocity note that hzdot is the TF from z to ydot lsim(hzdot,z,t) .....

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

42

Sinusoidal Road Surface Profile - Amplitude : 1 cm, Frequency : 5 rad/s 0.01

0.008

0.006

0.004

0.002 y [m]

Script m-files
This is what you get from the program defaults !
0 1 2 3 4 5 Time [s] 6 7 8 9 10

-0.002

-0.004

-0.006

-0.008

-0.01

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

43

Sinusoidal Road Surface Profile - Amplitude : 1 cm, Frequency : 5 rad/s

0.02 0.015 0.01 ydot [m/s] 0.005 0 -0.005 -0.01 -0.015 -0.02 0

Script m-files
You can modify the plots using the edit facility on the Matlab plot

5 6 7 Time [s] (sec)

10

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

44

Sinusoidal Road Surface Profile - Amplitude : 1 cm, Frequency : 5 rad/s 0.1 0.08 0.06 ydoubledot [m/s2] 0.04 0.02 0 -0.02 -0.04 -0.06 -0.08 -0.1

Script m-files
You can modify it using the edit facility on the Matlab plot
0 1 2 3 4 5 6 Time [s] (sec) 7 8 9 10

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

45

m-files
Function m-Files
Can accept input arguments and return output arguments. Internal variables are local to the function by default. Useful for extending the MATLAB language for your application.

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

46

Function m-files
function [Fx,Fy]=tireforces(munom,Fx,Fz,alpha,slip,vwl) ..... ..... .....

Call from the main program body : [Fxfl,Fyfl]=tireforces(munoml,Fxfl,Fzfl,alphafl,slipfl,vwlfl);

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

47

Time Response for LTI Systems : lsim


lsim(sys,u,t,x0) specifies the initial state vector x0 at time t(1) (for state-space models only). x0 is set to zero when omitted. lsim(sys1, sys2,..., u, t, x0) simulates the response of multiple LTI models sys1, sys2,... on a single plot. You can also specify a color, line style, and marker for each system, as in lsim(sys1,'r',sys2,'y--',sys3,'gx',u,t).

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

48

Time Response for LTI Systems : lsim


Draw the yaw velocity response for the vehicle specified below for a 3o step steering angle of the front wheels while travelling at 60 kph. Vehicle specifications : m=1310 [kg] J=1760 [kg.m^2] a=1.2 [m] b=1.4 [m] Cf=-34870 [N/rad] Cr=-31730 [N/rad]

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

49

Time Response for LTI Systems : lsim


% November 2003 % ----------------------% Example % Plots of sideslip angle and yaw velocity % for a step fronts wheel steering angle % --------------------------------------------------------% Enter vehicle parameters - in [kg], [kg.m^2] and [m] m=1310;J=1760;a=1.2;b=1.4;L=a+b; % Enter axle cornering stiffnesses - in [N/rad] Cf=-34870;Cr=-31730; % Enter forward speed of the vehicle in [kph] and convert to [m/s] ukph=60; u=ukph/3.6; . .

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

50

Time Response for LTI Systems : lsim


. . % Enter solution time range and increment - 0 to 2s by 0.01s increments t=0:0.025:2; % Enter front wheel steering angle variation with time in [deg] dfdeg(1:81)=3; % Express this for all t values ! % Convert to [rad] df=dfdeg*pi/180; % Plot figure(1) plot(t,dfdeg) xlabel('Time [s]') ylabel('Front Wheel Steering Angle [deg]') gtext('Vehicle Speed : 60 [kph]') % ------------------------------------------------------------------Prof. Dr. Y. Samim nlsoy ME 304 Control Systems 51

Time Response for LTI Systems : lsim


. . % Basic System Matrices % State variables are sideslip and yaw velocities A=[(Cf+Cr)/(m*u) (a*Cf-b*Cr)/(m*u)-u; (a*Cf-b*Cr)/(J*u) (a^2*Cf+b^2*Cr)/(J*u)]; B=[-Cf/m;-a*Cf/J]; % [Y]=[C]{x}+[D]{u} C=[1 0;0 1]; % The output will have two columns, for v and r D=[0;0]; . .

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

52

Time Response for LTI Systems : lsim


. . % Plot response figure(2) lsim(A,B,C,D,df,t) % This is going to give two plots, one for v(t) and the other for r(t). % If you prefer to produce your own plot(s), then you can store % the results in a matrix. % x=lsim(A,B,C,D,df,t) % Again, x will have the size 81x2, and the first column is going to % give variation of v(t) and the other r(t). % Then to plot variation of r % plot(t,x(:,2)) % To plot variation of v % plot(t,x(:,1)

Prof. Dr. Y. Samim nlsoy

ME 304 Control Systems

53

Vous aimerez peut-être aussi