matlab basics - ruk.usc.eduruk.usc.edu/books/yang-sssd/matlab basics.pdfmatlab basics inside b.1...

25
MATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control Flow B.6 Solution of Algebraic and Differential Equations B.7 Control System Toolbox (The material contained from this document comes from the book “Stress, Strain, and Structural Dynamics: An Interactive Handbook of Formulas. Solutions, and MATLAB Toolboxes” by Bingen Yang) Bingen Yang/April 2005 1

Upload: others

Post on 30-Sep-2020

9 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

MATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control Flow B.6 Solution of Algebraic and Differential Equations B.7 Control System Toolbox

(The material contained from this document comes from the book “Stress, Strain, and Structural Dynamics: An Interactive Handbook of Formulas. Solutions, and MATLAB Toolboxes” by Bingen Yang)

Bingen Yang/April 2005 1

Page 2: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

MATLAB is a premier software package that provides an interactive environment for technical computation, data analysis, graphics and visualization. MATLAB has many predefined functions (subroutines) that make numerical solution of engineering problems and computer programming much easier, compared to computing via other languages. B.1 Getting Started

After MATLAB is launched, a prompt >> appears in the command window. Right next to the prompt is a cursor blinking, indicating that the system is ready to receive commands. Assignment of Variables

In MATLAB, all variable names (scalars, vectors and matrices) have to be assigned numerical values prior to being used in an expression. The syntax of variable assignment is

variable name = an expression or a value

If the = sign and variable name are omitted in a statement, a name ans is automatically assigned by MATLAB. For instance, typing the following command (and hitting the Enter or Return key)

>> b=-1.5

yields the output (displayed in the command window)

b =

-1.5000 which defines a scalar b with value –1.5. But

>> -1.5

ans =

-1.5000 The statement

>> v=[1; -5; 13; 8]

or

>> v=[1 -5 13 8]’ defines a column vector

v =

1 -5 13 8

and the statement

Bingen Yang/April 2005 2

Page 3: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

>> w=[1 -5 13 8] defines a row vector

w =

1 -5 13 8 Furthermore

>> A=[1 3 5; 6 9 8; -2 0 8] produces a matrix

A =

1 3 5 6 9 8 -2 0 8

The MATLAB Workspace

All variables assigned in the command window are stored in a part of computer memory called the MATLAB workspace, and these variables can be recalled at any time as desired. A list of the variables ever assigned can be obtained by the MATLAB command who:

>> who

Your variables are:

A ans b v w

The variables that reside in the MATLAB can be saved in a binary data file for later use. This is done in one of the following two ways:

• Choose the Save Workspace As … from the File menu

• Use the MATLAB save command

>> save dataFile

which stores all the variables in the file dataFile.mat. To retrieve the saved data, either choose the Import Data … from the File menu, or use the MATLAB load command

>> load dataFile Character Strings

In MATLAB, single quotations (‘ ’) are used to define and store a string of characters as an array ASCII values. For example, the statement

>> Book = 'Stress, Strain, and Structural Dynamics’

Book =

Stress, Strain, and Structural Dynamics

Bingen Yang/April 2005 3

Page 4: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

defines variable Book as a representation of the character string “Stress, Strain, and Structural Dynamics.” The variable Book, when typed in the command window will display its content. The character string can also be shown by

>> disp(Book)

Stress, Strain, and Structural Dynamics

or

>> disp('Stress, Strain, and Structural Dynamics’) Stress, Strain, and Structural Dynamics

Here disp is a MATLAB function that display results (characters or numbers) without identifying variable names. Suppression of Output Display

If a statement is followed by a semicolon (;), the display of the output will be suppressed. >> A=[1 3 5; 6 9 8; -2 0 8];

assigns numerical values to matrix A, but does not show the result. Entering Several Statements on One Line

When separated by commas (,) or semicolons (;), several commands or statements can be placed on one lines. Compare the outputs of the following statements

>> a = 5, x = 2, y = 8

>> a = 5; x = 2; y = 8; Mathematical Operators

MATLAB uses the following operators in mathematical expressions:

+ addition − subtraction * multiplication / division \ left division ^ power

For instance, a*(3.5)^3+b/c represents the mathematical expression a b . 3(3.5) /+ c

Bingen Yang/April 2005 4

Page 5: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Predefined Variables

MATLAB has several predefined variables, some of which are shown below:

i, j imaginary unit 1− pi 3.14159...π = Inf infinity ( ∞ ) NaN not a number

>> z=2-5*j;

assigns a complex number 2 5, z j j= − = −1 . These predefined variables, however, can be overwritten for other usage. For example,

>> j=[1 2; 3 4]; assigns j as a 2-by-2 matrix.

In addition, the letter e is used to express powers of base 10. To assign a variable d with value − × , 32.5 10

>> d=-2.5e3

d =

-2500 Mathematical Functions

MATLAB offers many predefined mathematical functions for technical computations. Table B1 lists some commonly used functions, where variables x and y can be numbers, vectors or matrices. As an example, the value of the expression sin( ) 10ay e x y−= + for a = 5, x = 2, and y = 8 is computed by

>> a = 5; x = 2; y = 8;

>> y = exp(-a)*sin(x) + 10*sqrt(y)

y =

28.2904 Online Help

Typing “help FUN” will display in the MATLAB command window what the function FUN is, and how to use it. For instance

>> help rem displays the information about function rem. Also, information about MATLAB functions can be accessed by choosing MATLAB Help from the Help menu.

Bingen Yang/April 2005 5

Page 6: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Table B1. Elementary functions

Function Meaning Function Meaning

sin(x) Sine log(x) Natural logarithm

cos(x) Cosine log10(x) Common logarithm

tan(x) Tangent abs(x) Absolute value

asin(x) Arcsine sign(x) Signum function

acos(x) Arcosine max(x) Maximum value

atan(x) Arctangent min(x) Minimum value

sinh(x) Hyperbolic sine ceil(x) Round towards +∞

cosh(x) Hyperbolic cosine floor(x) Round towards −∞

tang(x) Hyperbolic tangent round(x) Round to nearest integer

sinh(x) Hyperbolic sine rem(x,y) Remainder after division

cosh(x) Hyperbolic cosine real(x) Complex real part

tang(x) Hyperbolic tangent imag(x) Complex imaginary part

exp(x) Exponential angle(x) Phase angle

sqrt(x) Square root conj(x) Complex conjugate Number Display Formats

While computations in MATLAB are carried out in double precision, the numerical results displayed in the command window may only have four digits after the decimal point. The user can change the display format by choosing the Preferences … from the File menu, or use the following format commands

format Default. Scaled fixed point format with 5 digits. format long Scaled fixed point format with 15 digits. format short e Floating point format with 5 digits. format long e Floating point format with 15 digits. An example is shown below:

>> 1/7

ans =

0.1429 >> format long; 1/7

ans =

0.14285714285714

Bingen Yang/April 2005 6

Page 7: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

B.2 Matrix and Vector Manipulations Matrix Operations

Most matrix operations in MATLAB follow the way by which conventional mathematical expressions are used in textbooks and technical references. Transposition

The transpose of a real matrix or vector is obtained by the prime or apostrophe (‘): >> A = [1 2; 3 4];

>> B=A'

B =

1 3 2 4

The transpose of a complex matrix or vector is obtained by the dot-prime (.‘):

>> C = [1 2-j; 3+j*5 4];

>> D=C.'

D =

1.0000 3.0000 + 5.0000i 2.0000 - 1.0000i 4.0000

Note: Use of the prime alone, C’, produces the complex conjugate transpose of C. Addition and subtraction

The symbols + and – are used for adding and subtracting matrices.

>> C=A+B

C =

2 5 5 8

Multiplication

The symbol * is used for matrix multiplication. For instance, >> C*A

ans =

17 24 29 42

and

>> D = 10*C

Bingen Yang/April 2005 7

Page 8: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

D =

20 50 50 80

Incremental Generation of Vectors

Let n and be two real numbers, n1 2n 1 n2≤ . The statement

v = 1 2:n n generates a row vector v containing the number from to with unit increment. The statement

1n 2n

w = 1 2: :n n n∆

creates a row vector w containing the numbers from n to with increment . For instance, 1 2n n∆

>> x=-1:4

x =

-1 0 1 2 3 4 >> y=0:pi/3:pi

y =

0 1.0472 2.0944 3.1416 Vector y can also be generated by the MATLAB function linspace as follows

>> y = linspace(0, pi, 4)

Array Addressing

Consider the matrix A =

1 3 5 6 9 8 -2 0 8

The statement

>> A(1:2,:) specifies the first two rows of A

ans =

1 3 5 6 9 8

Bingen Yang/April 2005 8

Page 9: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

The statement

>> A(2:3, [1 3]) specifies a submatrix that is obtained by deleting the first row and second column of A:

ans =

6 8 -2 8

In MATLAB, individual matrix elements are referenced by their subscripts. For instance,

A(2,3) refers to the element of A in the second row and third column.

>> A(2,3)=A(3,1)-7 results in

A =

1 3 5 6 9 -9 -2 0 8

The above array addressing is also applicable to vectors.

Element-by-Element Array Operations

Besides the standard matrix/vector operations, MATLAB performs element-by-element array operations (multiplication, division, and power) among matrices or vectors of the same dimensions. To illustrate this special feature, consider two vectors of n elements

[ ] [ ]1 2 1 2,n na a a a b b b b= =L L

Let g be a scalar. Some basic element-by-element array operations are given as follows: Array multiplication [ ]1 1 2 2.* * * *n na b a b a b a b= L

Array division [ ]1 1 2 2. / / / /n na b a b a b a b= L

Array powers [ ]1 1 2 2.^ ^ ^ ^n na b a b a b a b= L

Scalar addition [ ]1 2 na g a g a g a g+ = + + +L Here, operators .* (dot multiplication), ./ (dot division), and .^ (dot power) are used for element-by-element array operations. These operators make programming for computation compact and efficient. For example, to evaluate the values of the function at

, write

2 21 sinty t e−= − 5t0,0.1,0.2,...,0.8t =

Bingen Yang/April 2005 9

Page 10: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

>> t=0:0.1:0.8;

>> y=1-t.^2.*exp(-2*t).*sin(5*t)

y =

1.0000 0.9961 0.9774 0.9507 0.9346 0.9450 0.9847 1.0424 1.0978

The above-mentioned element-by-element operations are also applicable to matrices of the same dimensions. For the two matrices

1 2 5 6,

3 4 7 8A B

= =

>> A./B

ans =

0.2000 0.3333 0.4286 0.5000

and

>> A-1

ans =

0 1 2 3

Matrix Functions

MATLAB provides many matrix functions for various matrix/vector manipulations; see Table B2 for some of these functions. Use the online help of MATLAB to find how to use these functions.

Table B2 Matrix functions

Function Utility

det Determinant

diag Diagonal matrices and diagonals of a matrix

eig Eigenvalues and eigenvectors

expm Matrix exponentials

eye Identity matrix

inv Matrix inverse

norm Matrix and vector norms

ones Matrix containing all elements ones

rank Number of linearly independent rows or columns

zeros Matrix containing all elements zeros

Bingen Yang/April 2005 10

Page 11: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

As an example, consider the following matrix >> A = [1 0 5; 2 -3 1; 4 4 7];

The inverse of matrix A is obtained as

>> B=inv(A)

B = -0.3333 0.2667 0.2000 -0.1333 -0.1733 0.1200 0.2667 -0.0533 -0.0400

The determinant of matrix A is

>> det(A)

ans =

75 The eigenvalues and eigenvectors of matrix A are given by

>> [U,V]=eig(A)

U =

0.4847 0.6331 0.6331 0.1420 0.3504 - 0.5102i 0.3504 + 0.5102i 0.8631 -0.4371 + 0.1581i -0.4371 - 0.1581i

V = 9.9042 0 0 0 -2.4521 + 1.2489i 0 0 0 -2.4521 - 1.2489i

where the diagonal elements of matrix V are the eigenvalues, and the columns of matrix U are the associate eigenvectors.

Table B3 Functions for polynomials

Function Utility

conv Polynomial multiplication

deconv Polynomial division

poly Convert roots to polynomial

polyval Evaluate a polynomial

roots Find polynomial roots

Bingen Yang/April 2005 11

Page 12: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Polynomial Manipulations

In MATLAB, a polynomial 11 1( ) n n

n n nP x a x a x a x a−− 0= + + +L + is expressed by a row or

column vector, like [ ]1 1 0n np a a −= a aL that contains the coefficients of the polynomial ordered by descending powers. MATLAB has some functions for polynomial manipulations; see Table B3.

For the cubic equation

3 2- 2 23 0r r + = its roots are computed by

>> roots([1 -2 0 23]) ans = 2.1550 + 2.3048i 2.1550 - 2.3048i -2.3101

The product of polynomials and 2

1( ) 3 2 5P x x x= + + 22 ( ) 6 7 1P x x x= + − is obtained by

>> p1=[3 2 5]; p2=[6 7 -1];

>> p=conv(p1,p2)

p =

18 33 41 33 -5

B.3 Graphics

A collection of MATLAB functions is available for sophisticated graphics and visualization of data. Listed in Table B4 are some of them. Use the online help to learn how to use these functions.

As a demonstrative example, consider function 21 (cos3 0.2sin 3t )x e t−= − − t

4

. The statements

>> t=linspace(0, 4, 101); >> x = 1-exp(-2*t).*(cos(3*t)-0.2*sin(3*t)); >> plot(t,x) >> grid; xlabel('t'); ylabel('x') >> title('Function x vs time t')

create 101 data points over the range 0 t≤ ≤ , and plot the curve x versus t in Fig. B1.

Bingen Yang/April 2005 12

Page 13: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Table B4 Functions for graphics

Function Utility

plot Linear plot

axis Axis scaling

grid Add grid lines

title Place graph title

xlabel x-axis label

ylabel y-axis label

legend Graph legend

subplot Divide a graphic window into multiple ones

plot3 Plot lines and points in three dimensions

Fig. B1

Fig. B2

Now consider another function v e . Functions x and v can be plotted in one figure:

2 (2.6cos3 1.6sin 3 )t t t−= +

>> v = exp(-2*t).*(2.6*cos(3*t)+1.6*sin(3*t)); >> plot(t,x,t,v, ':') >> xlabel(‘t’) >> legend('x', 'v')

which produces Fig. B2. In the plot command, symbol ‘:’ is used to set the dotted line style for the y curve. Some available line styles are given below

Bingen Yang/April 2005 13

Page 14: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Symbol Line Style

− solid : dotted −. dashdot −− dashed Typing help plot in the command window shows more information about line styles.

The x and v can also be plotted in two

subplots in one figure window:

>> subplot(2,1,1) >> plot(t,x) >> grid,xlabel('t'), ylabel('x') >> title('x versus t') >> subplot(2,1,2) >> plot(t,v) >> grid, xlabel('t'), ylabel('v') >> title('v versus t')

which produces the x- and v- curves in two subplots in Fig. B3. Here, function subplot partitions the graphic window into two parts, and function plot generates a curve for each part.

Fig. B3

A three-dimensional line can be generated by the command plot3(x, y, z), where x, y, z are vectors of the same length. For example

>> z=linspace(0,1,201); >> x=exp(-2*z).*cos(20*z); >> y = exp(-2*z).*sin(20*z); >> clf >> plot3(x,y,z) >> xlabel('x'), ylabel('y'), zlabel('z') >> grid

produces the curve

2 2cos(20 ), sin(20 ),t tx e t y e t− −= = z t=

1

for 0 ; see Fig. B4. t≤ ≤

Fig. B4

Bingen Yang/April 2005 14

Page 15: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

The aspect ratio of a plot displayed in the MATLAB figure can be controlled as follows:

axis equal sets the aspect ratio so that the x, y and z coordinates are equal in scale.

axis square sets the current axis box square in size.

axis normal sets the aspect ratio back to the default setup. Type help axis in the command window to find out more in detail. B.4 M-Files

In MATLAB, there are two types of M-files: script M-files and function M-files. These files are called M-files because their names must end with the extension “.m”, such as test.m. Script M-Files

MATLAB allows the user to put a number of commands in a simple text file, and execute the

commands contained in the file as if they were typed at the prompt in the command window. All variables assigned in the file reside in the MATLAB workspace. This type of files is called script files. Execution of the commands in a script file simply needs to type the name of the M-file in the MATLAB command window. Script M-files are useful for evaluation of a large number of commands in different cases of variable values.

A script file can be created by choosing New from the File menu and by selecting M-file, which launches a text editor. Use this text editor to type the desired MATLAB commands. Choose Save or Save As … from the File menu to name and save the script file on the computer. The following is an example of script M-file, which computes the free vibration of a spring-mass system for given initial displacement x0 and initial velocity v0.

% freevib.m - a script file for free vibration % of a spring-mass system % x0 – initial displacement % v0 – initial velocity t=linspace(0,5,201); wn = pi; % wn = natural frequency x = x0*cos(wn*t)+v0/wn*sin(wn*t); v = -x0*wn*sin(wn*t)+v0*cos(wn*t); plot(t,x, t,v,':') grid, xlabel('t') legend('displacement', 'velocity')

In MATLAB, all the text after the percentage sign (%) is taken as a comment statement, and

will not be executed.

>> x0 = 0.1; v0 = 0;

>> freevib

Bingen Yang/April 2005 15

Page 16: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

plots the vibration of the system in Fig. B5(a) for x0 = 0.1 and v0 = 0. Also

>> x0 = 0; v0 = 0.4;

>> freevib

plots the vibration of the system in Fig. B5(b) for x0 = 0 and v0 = 0.4. In both cases, the script file freevib.m has been called to execute the commands in it.

(a)

(b)

Fig. B5 Function M-Files

Function M-files in MATLAB have similar functionalities of subroutines or procedures in

other computer programming languages such as Fortran and C. See the following example.

function x = frvibration(x0, v0) % FRVIBRATION – compute and output displacement x of % a spring-mass system for given initial displacement x0 and % initial velocity v0 t=linspace(0,1,10); wn = pi; % wn = natural frequency x = x0*cos(wn*t)+v0/wn*sin(wn*t);

Function frvibration, stored in a file under the name frvibration.m, takes x0 and v0 as input variables, and returns vector x as an output variable. For instance,

>> frvibration(0.1, 0)

ans =

0.1000 0.0940 0.0766 0.0500 0.0174 -0.0174 -0.0500 -0.0766 -0.0940 -0.1000

A function M-file contains the word function at the beginning of the first line, such as

function outputvar = FunName(inputvar1, inputvar2, …)

Bingen Yang/April 2005 16

Page 17: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

or

function [outputvar1, outputvar2, …] = FunName(inputvar1, inputvar2, …) where FunName is the function name, inputvar1, inputvar2, … are input variables, and outputvar, outputvar1, outputvar2, … are output variables. The rest of the lines in the function file are commands or comments (texts after the percentage sign %). As a rule, the output variables of the function must be assigned within the function. Also, function FunName should be stored in a file named FunName.m. A function M-file can be created the same way as a script M-file.

Like script M-files, a function M-file must have an extension “.m”. However, a function M-

file is different from a script file in that the function interacts with the MATLAB workspace only through its input and output variables. The intermediate variables contained in the function do not appear in, or interact with the MATLAB workspace; they reside locally in a separate workspace of the function. For instance, the intermediate variables of function frvibration are t and wn, which are not created in the MATLAB workspace. Set MATLAB Search Path

If M-files and data files (files with extension .mat) are stored in a folder that is not on the MATLAB Search Path, MATLAB cannot find them. In this case, one can add the desired folder to the MATLAB Search Path by choosing the Set Path … form the File menu and selecting the Add Folder … button. Another way to resolve this problem is to put those files to be used in the MATLAB work folder, which is located inside the MATLAB program folder. To find more about the MATLAB Search Path, go to the MATLAB Help from the Help menu. B.5 Control Flow

Like other computer programming languages, MATLAB has some decision-making structures for control of command execution. These decision-making or control-flow structures include for loops, while loops, and if-else-end constructions. Control-flow structures are often used in scrip M-files and function M-files.

for Loops

A for loop in general has the form for x = array commands end

which allows a set of commands to be repeated a fixed number of times. Here, array is a vector or matrix, and the commands between the for and end statements are executed once for each column of array. For instance,

>> for i=1:5

Bingen Yang/April 2005 17

Page 18: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

a(i)=i^2+1;

end

assigns vector a with elements i for i = 1,2,.., 5: 2 1+

>> a

a =

2 5 10 17 26

for loops can be nested, as shown in the following example:

>> for i = 1:3 for j = 1:3 b(i,j) = sin(i*pi/4)*sin(j*pi/4); end end >> b

b =

0.5000 0.7071 0.5000 0.7071 1.0000 0.7071 0.5000 0.7071 0.5000

which assigns matrix b with elements sin sin4 4iji jb π π

= for i j, 1, 2,3= .

Table B5 Rational and logical operators

Relational Operator Logical Operator

> less than <= less than or equal to > greater than >= greater than or equal to = = equal to ~ = not equal to

& AND operator | OR operator ~ NOT operator

Logical Statements

MATLAB has certain rational operators and logical operators for answers to True-False questions in decision making; see Table B5. A logical statement is one that contains relational and logical operators. The output of a logical statement is one for True and zero for False. For example

>> y = (5>6)

y =

Bingen Yang/April 2005 18

Page 19: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

0

>> (sin([0 1 2 3 4 5]) > 0) & (cos([0 1 2 3 4 5]) < 0)

ans =

0 0 1 1 0 0 Logical statements are often used in while loops and if-else-end constructions.

while Loops

A while loop is used to evaluate a set of commands an indefinite number of times, which is reinforced by a logical statement. A while loop has the form

while expression commands end

where expression is a logical statement. The commands between the while and end statements are executed as long as the logical statement is true. For example,

>> n = 1; y = 2;

>> while y+0.00001 < exp(1) n=n+1; y = (1+1/n)^n; end

>> format long

>> y, n

y =

2.71827182846131

n =

135913

The above while loop computes the expression 11n

yn

= +

2.718281828459

e≥

for a large enough n such that

, where e is the irrational number . 0.00001y + L

if-else-end Constructions

An if-else-end construction is used for conditional evaluation of several sequences of commands. The general form of an if-else-end construction is

if condition1 commands evaluated if condition1 is True elseif condition2

Bingen Yang/April 2005 19

Page 20: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

commands evaluated if condition2 is True elseif …

M

else commands evaluated if none of the about expressions are True end

where condition1, condition2 … are logical statements. Two simplified versions of the above if-else-end construction are

if condition commands evaluated if condition is True end

and

if condition commands evaluated if condition is True else commands evaluated if condition is False end

The above-mentioned forms of if-else-end constructions can be combined and nested in use.

As an example, consider the following function M-file:

function x = quadeq(a, b, c) d=b^2-4*a*c; disp(' ') if a == 0 disp('This is not a quadratic equation'); return end if d > 0 disp('The equation has two different real roots') elseif d == 0 disp('The equation has two identical real roots') else if b == 0 disp('The equation has two imaginary roots') else disp('The equation has two complex roots') end end x1 = (-b+sqrt(d))/2/a; x2 = (-b-sqrt(d))/2/a; x = [x1; x2];

Bingen Yang/April 2005 20

Page 21: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

which uses if-else-end constructions to tell the type of the roots for a quadratic equation . 2 0ax bx c+ + =

>> x=quadeq(1,2,3) The equation has two complex roots

x =

-1.0000 + 1.4142i -1.0000 - 1.4142i >> x=quadeq(1,4,4) The equation has two identical real roots

x =

-2 -2

B.6 Solution of Algebraic and Differential Equations

MATLAB provides several useful functions for solution of algebraic and differential equations; see Table B6, where inv, roots, fzero, fmins, ode23, and ode45 are MATLAB functions, and \ is the left division operator. Use the online help to find how to use these functions.

Table B6 Solution of algebraic and differential equations

Equation Type MATLAB Command

System of linear algebraic equations

Ax = y

x = inv(A)*x or

x = A\y

Polynomial equation

11 1 0n n

n na x a x a x a−−+ + + +L 0 =

0x = roots([ ]) 1 1n na a a a− L

Nonlinear algebraic equation of one variable

( ) 0f x =

x = fzero(‘FUN’, x0)

Nonlinear algebraic equation of multiple variables

( ) 0f x =

where x is a vector.

x = fmins(‘FUN’, x0)

Linear and nonlinear differential equations

( , )d x f x tdt

=

where x is either a scalar or a vector.

[t, x] = ode23(‘FUN’, tspan, x0)

or

[t, x] = ode45(‘FUN’, tspan, x0)

Bingen Yang/April 2005 21

Page 22: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Example B1 For the system of linear algebraic equations

1

2

3

1 5 2 30 3 4 14 7 10 8

xxx

− = −

the solution is obtained by

>> A=[1 -5 2; 0 3 -4; 4 7 10];

>> f=[3; -1; 8];

>> x=A\f

x =

1.9474 -0.1579 0.1316

The solution can also be obtained by inv(A)*f. Example B2 To solve the nonlinear algebraic equation

( ) 2 sin 0xf x e x−= − = for the smallest root, the following function M-file is generated for function fzero:

function f = NLfunc(x) f = 2*exp(-x)-sin(x);

The initial guess of the solution is 0x = 0. A root of the nonlinear equation is obtained by

>> fzero(‘NLfunc’, 0)

ans =

0.9210

The commands

>> x=linspace(0,2,2001); >> f = NLfunc(x); >> plot(x,f) >> grid; xlabel('x'); ylabel('f')

plot the function f(x) versus x in Fig. B6, which shows that x = 0.9210 is the smallest root.

Fig. B6

Bingen Yang/April 2005 22

Page 23: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Example B3 The differential equation

2sin( ) 0

(0) 0.2, (0) 0.5

x x x

x x

+ + =

= =

&& &

&

is solve by the MATLAB function ode45. To this end, the equation is rewritten as the first-order state equations

1 2

2 2 2sin( )

x x

1x x x

=

= − −

&

&

with the initial conditions , where 1 2(0) 0.2, (0) 0.5x x= = 1x x= and 2x x= & . The following function M-file, which is required by function ode45, is created based on the state equations:

function f = sfunc(t,x) f = zeros(2,1); f(1) = x(2); f(2) = -x(2)-2*sin(x(1));

The commands

>> [t,x]=ode45(‘sfunc’, [0 5], [0.2 0.5]); >> plot(t,x(:,1),t, x(:,2), ':') >> grid; xlabel('t'), >> legend('x1', 'x2')

yield 1x and 2x for , which are plotted against t in Fig. B7. Note that the execution of the ode45 command calls for the function sfunc.

0 t≤ ≤ 5

Fig. B7

Bingen Yang/April 2005 23

Page 24: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

B.7 Control System Toolbox

Besides the general features and functions described previously, MATLAB provides collections of function M-files called toolboxes, which solve problems in specific areas or disciplines. Listed in Table B7 are some functions from the Control System Toolbox. These functions are useful in the design of feedback controllers for mechanical systems and flexible structures; see Chapters 11 and 12 for instance.

Table B7 Functions from the Control System Toolbox

Transfer Function Formulation tf Create a transfer function model zpk Create a zero-pole-gain model series Series interconnection of two blocks (transfer functions) parallel Parallel interconnection of two blocks (transfer functions) feedback Obtain the transfer function of a feedback control system

State-Space Formulation ss Create a state-space model ss2tf State-space to transfer function conversion tf2ss Transfer function to state-space conversion minreal Minimal realization and pole-zero cancellation ctrb Compute controllability matrix obsv Compute observability matrix

System Response impulse Impulse response step Step response lsim Response to arbitrary inputs

Root Locus rlocus Root locus sgrid Generate an s plane grid of constant damping factors and natural

frequencies Frequency Response

freqresp Frequency response bode Bode plot of the frequency response nyquist Nyquist plot margin Gain and phase margins nichols Nichols frequency response

Controller Design Tools rlocfind Interactive root locus gain determination rltool SISO system design tool via root locus sisotool Open the SISO Design Tool place Pole placement technique lqr Linear-quadratic regulator design

Bingen Yang/April 2005 24

Page 25: MATLAB Basics - ruk.usc.eduruk.usc.edu/Books/yang-sssd/MATLAB Basics.pdfMATLAB Basics Inside B.1 Getting Started B.2 Matrix and Vector Manipulations B.3 Graphics B.4 M-Files B.5 Control

Example B4 Consider a dynamic system described by the transfer function

3 2( ) 2.5( )( ) 2 5 20 18

Y s sG sR s s s s

+= =

+ + +

The system transfer function is created by

>> num = [1 2.5]; >> den = [2 5 20 18]; >> sys = tf(num,den)

Transfer function: s + 2.5 --------------------------------- 2 s^3 + 5 s^2 + 20 s + 18

The response of the system under a unit impulse input ( ) ( )r t t= δ is plotted in Fig. B8 by

>> impulse(sys)

Here vectors num and den contain the coefficients of the numerator and denominator of the transfer function, respectively.

Furthermore, let the system be under feedback control. Assume that the closed-loop characteristic equation is

1 ( )k G s 0+ ⋅ = where k is a positive feedback gain parameter. The closed-loop root loci versus the parameter k are plotted in Fig. B9 by

>> rlocus(sys)

Fig. B8

Fig. B9

Bingen Yang/April 2005 25