30
1. MATLAB In this set of information files we provide an introduction to the software applications package MATLAB. You may ask “why have we chosen MATLAB?”. The reason is that as well as being a good teaching environment, the package is an Industry Standard. We shall use the package to support the curriculum in a variety of courses. However, this won’t be your only use of the package. In later courses you may well meet MATLAB toolboxes associated with particular applications. So, what is MATLAB? MATLAB is an interactive system for doing numerical computations. A numerical analyst called Cleve Moler wrote the first version of MATLAB in the 1970s. It has since evolved into a successful commercial software package. MATLAB relieves you of a lot of the mundane tasks associated with solving problems numerically. This allows you to spend more time thinking, and encourages you to experiment. MATLAB makes use of highly respected algorithms and hence you can be confident about your results. Powerful operations can be performed using just one or two commands. You can build up your own set of functions for a particular application. MATLAB 1.1 26 March, 2002

MATLAB 1 - Introduction

Embed Size (px)

Citation preview

Page 1: MATLAB 1 - Introduction

1. MATLABIn this set of information files we provide an introduction to the software applications

package MATLAB. You may ask “why have we chosen MATLAB?”. The reason is

that as well as being a good teaching environment, the package is an Industry

Standard. We shall use the package to support the curriculum in a variety of courses.

However, this won’t be your only use of the package. In later courses you may well

meet MATLAB toolboxes associated with particular applications. So, what is

MATLAB?

MATLAB is an interactive system for doing numerical computations.

A numerical analyst called Cleve Moler wrote the first version of MATLAB in the

1970s. It has since evolved into a successful commercial software package.

MATLAB relieves you of a lot of the mundane tasks associated with solving

problems numerically. This allows you to spend more time thinking, and

encourages you to experiment.

MATLAB makes use of highly respected algorithms and hence you can be

confident about your results.

Powerful operations can be performed using just one or two commands.

You can build up your own set of functions for a particular application.

Excellent graphics facilities are available and the pictures can be inserted into

Word documents with very little difficulty.

You will use the material in this and the other MATLAB information files as your

principal source of information, the actual files that you use will depend on your

course and you may well not need all those listed in the next section. We suggest that

you work through the recommended material in order. However, that is not necessary

and you may jump about from section to section as you wish. There will be no formal

MATLAB lectures, the support will be available in regular laboratory sessions in the

FEIS PC Teaching Laboratories, D410 or A625.

MATLAB 1.1 26 March, 2002

Page 2: MATLAB 1 - Introduction

1.1 MATLAB information filesMATLAB 1 Introduction

MATLAB 2 Plotting graphs

MATLAB 3 m-files

MATLAB 4 Vectors

MATLAB 5 Matrices

MATLAB 6 Calculus

MATLAB 7 Programming

MATLAB 8 Further MATLAB

MATLAB 9 Simulink

MATLAB 10 Fourier series

Appendix

You won’t be using all these files in your current course. Also, since these files will

be used by people on a variety courses there may be one or two subsections which are

not relevant to your studies at present. The necessary information will be posted on

StudyNet.

1.2 Starting upYou will be working in a Windows environment. Click on the Start button in the

bottom left-hand corner of the screen. Choose Programs then MATLAB Release 12

then MATLAB R12. The MATLAB command window and two other windows will

eventually appear together with the statement ‘To get started, select “MATLAB” Help

from the Help menu’, see Figure 1.1.

MATLAB 1.2 26 March, 2002

Page 3: MATLAB 1 - Introduction

Figure 1.1. MATLAB windows.

You do not need to select Help, you can start immediately with the MATLAB

command prompt:>>

You should save a record of your session and any files that you create. The procedure

for doing this is described in section 1.2.

1.3 MATLAB laboratory workshop exercisesThe purpose of these exercises is to help you to get to know the MATLAB

environment and to support your understanding of the mathematical techniques which

are presented in the lectures. The exercises are not exhaustive, they give you an

introduction to the topic and you should find other exercises to try. In particular the

exercises in the text book or tutorial sheets would be a good place to start.

You should keep a record of your MATLAB sessions, collecting them together in a

laboratory workshop folder. This workbook will be collected towards the end of the

course and will comprise part of the coursework assessment.

MATLAB 1.3 26 March, 2002

Page 4: MATLAB 1 - Introduction

The best way to keep a record of your session is to use the command diary. When

you start your session type the command>> diary X:yourfile1.txt>> % YOUR NAME, session number>> date

ans =

22-Jan-2002

Then everything you type will be recorded in the file yourfile1.txt on your floppy or

zip disk where X is the external device drive onto which your work is be copied, either

a floppy or zip disk. The name of the drive depends on the laboratory in which you

are working, see local details. It’s up to you what name you use for yourfile1 but you

should write your name on the next line which is started with a percentage sign, %.

This is MATLAB’s comment symbol, anything which follows % is ignored by

MATLAB so you can use it to make comments during your sessions. You should use

a different file for each session so your second session would be saved in file

yourfile2.txt. These files, will be used to produce your workshop folder. We suggest

that you print them at regular intervals rather than wait until the end of the course

when it may be inconvenient to print all the files. Below you can see the start to a

typical session.>> diary a:alan1.txt % a is the floppy disc drive>> % ALAN DAVIES, session 1>> format compact>> date

ans =

22-Jan-2002>> format compact>> pians = 3.1416>> diary off % session is finished – close diary>> quit

MATLAB 1.4 26 March, 2002

Page 5: MATLAB 1 - Introduction

The diary command will not save any plots that you may have produced. To save

these you must save them to a file, e.g. a Word file, as explained in section 2.5.

Usually we use MATLAB in a systematic manner to develop the solution to a

problem. In the MATLAB information files we are running through a series of

exercises in a which is somewhat different manner. In order that earlier results do not

interfere with current calculations it is a good idea to start each subsection with the

two commands>> clear all>> format short

this should ensure that your results will be in the same format as those in the files. It

is a matter of good practice to use the clear all command regularly in your work

unless you are very sure that you do not wish to erase earlier results.

1.4 MATLAB as a calculatorThe basic arithmetic operators are + - * / ^ and these are used in conjunction with

brackets: (). The symbol ^ is used to get exponents, i.e. powers: 2^4=16.

You should type in the commands shown following the prompt: >>>> 2+3/4*5ans = 5.7500>>

Now, is this calculation performed as 2+3/(4*5) or 2+(3/4)*5?

MATLAB works according to the priorities:

1. quantities in brackets,

2. powers 2+3^22+9=11,

3. * /, working left to right (3*4/5=12/5),

4. + -, working left to right (3+4-5=7-5),

Thus, the earlier calculation was for 2+(3/4)*5 by priority 3.

MATLAB 1.5 26 March, 2002

Page 6: MATLAB 1 - Introduction

1.5 Numbers and formatsMATLAB recognises several different kinds of numbers, see Table 1.1

Table 1.1. MATLAB numbers.

Type Examples

Integer

Real

Complex

Inf

NaN

1362, 217897

1.234, 10.76

3.21 4.3i (i= )

Infinity (result of dividing by 0)

Not a Number, 0/0

The ‘e’ notation is used for very large or very small numbers:-1.3412e+03=-1.3412103=-1341.2

-1.3412e-01=-1.341210-1=-0.13412

All computations in MATLAB are done in double precision, which means about 15

significant figures. The format, the way in which MATLAB prints numbers, is

controlled by the ‘format’ command, see Table 1.2. Type help format for a full list.

Table 1.2. MATLAB format commands.

Command Example of output for 10*pi>> format short>> format long>> format short e>> format long e>> format rational>> format compact>> format loose

31.4162 (4 decimal places)3.14159265358979 (14 decimal places)

3.1416e+001 (e+x means )

3.141592653589793e+0013550/113 (answer as a fraction)Suppresses extra line feedsPuts back extra line feeds (default)

Should you wish to switch back to the default format then format will suffice.

The command>> format compact

is also useful in that it suppresses blank lines in the output thus allowing more

information to be displayed.

MATLAB 1.6 26 March, 2002

Page 7: MATLAB 1 - Introduction

1.6 VariablesConsider the following calculations:

>> 2+4^3ans = 66>> ans/3ans = 22

The result of the first calculation is labelled ans by MATLAB and is used in the

second calculation where its value is changed. However, we can use our own names

to store numbers:>> a=2+4^3a = 66>> b=a/3b = 22

so that a has the value 66 and and the values can be used in subsequent

calculations. These are examples of assignment statements in which values are

assigned to variables. Each variable must be assigned a value before it may be used

on the right-hand-side of an assignment statement.

1.7 Variable namesLegal names consist of any combination of letters and digits, starting with a letter. It

is very important to remember that MATLAB commands are case-sensitive, i.e. you

must distinguish between lower case and upper case characters.

These names are allowable:NetCost, Left2Pay, x3, X3, z25c5

These are not allowableNet-Cost, 2pay, %x, @sign

Use names that reflect the values they represent.

There are special names that you should avoid using

eps (=2.2204e-16=2-54),

the largest number such that 1+eps is indistinguishable from 1.

MATLAB 1.7 26 March, 2002

Page 8: MATLAB 1 - Introduction

pi ( =3.14159…)

If you wish to do arithmetic with complex numbers, both i and j have the value

unless you change them.>> i,j, i=2ans = 0 + 1.0000ians = 0 + 1.0000ii = 2

NB. MATLAB recognises both i and j as but it always returns i and not j.

MATLAB is case-sensitive, i.e. upper case and lower case symbols are considered to

be different variables.>> pians = 3.1416>> Pi??? Capitalized internal function Pi; Caps Lock may be on.

MATLAB doesn’t recognise Pi, it looks for a variable with the name Pi. The line

beginning ??? and in red text is a commentary by MATLAB indicating where the

error may arise.

1.8 Suppressing outputWe often do not want to see the result of intermediate calculations. To do this we

terminate the assignment statement or expression with a semi-colon.>> x=9; y=2*x/3; z=y^2+y*sqrt(x)z = 54

The values of x and y are hidden. We also note here that we can place several

statements on one line, separated by commas or semi-colons.

It is a good idea to get used to using the semi-colon especially when using arrays. It

is possible to have pages and pages of output. If you find a calculation going on and

on you can stop it by pressing the keys Ctrl and C simultaneously.

MATLAB 1.8 26 March, 2002

Page 9: MATLAB 1 - Introduction

1.9 Keyboard accelerators

We can recall previous MATLAB commands by using the and cursor keys.

Repeatedly pressing will review the previous commands the most recent first. To

re-execute the command simply press the return key. To edit, use the cursor keys

to move backwards and forwards through the line. Characters may be

inserted by typing at the current cursor position or deleted using the Del key. This

process is most commonly used when long command lines have been mistyped or

when you want to re-execute a command that is very similar to one used previously.

To recall the most recent command starting with f, say, type f at the prompt followed

by . Similarly, typing fo followed by will recall the most recent command starting

with fo.

1.10 Built-in functionsTrigonometric functions

Those recognised by MATLAB are sin, cos, tan and their arguments must be in

radians. e.g. to work out the coordinates of a point on a circle of radius 6 centred at

the point and having an elevation radians:

>>format short>> x=1+6*cos(pi/3), y=2+6*sin(pi/3)x = 4.0000y = 7.1962

The inverse trig functions are called asin, acos, atan, as opposed to the usual arcsin

or sin-1 etc., and the result is in radians.>> acos(1/2), asin(-1), atan(1)ans = 1.0472ans = -1.5708ans = 0.7854>> % check>> pi/3, -pi/2, pi/4ans = 1.0472

MATLAB 1.9 26 March, 2002

Page 10: MATLAB 1 - Introduction

ans = -1.5708ans = 0.7854

Other elementary functions

These include sqrt, exp, log, log10>> x=4, sqrt(x), exp(x), log(x), log10(x^2-6)x = 4ans = 2ans = 54.5982ans = 1.3863ans = 1

N.B. log10 gives logs to the base 10.

exp denotes the exponential function, , and its inverse function is log.

We have

N.B. .

>> format long e>> exp(log(9)), log(exp(9))ans = 9.000000000000002e+000ans = 9

and we see a very small rounding error in the first calculation. A more complete list

of elementary functions is given in the Appendix.

We can perform calculations to any prescribed precision. MATLAB’s vpa command

has a default precision of 32 digits, however we can prescribe the number of digits as

in the following example in which we shall calculate :>> exp(1)^pians = 23.1407>> format long>> exp(1)^pi

MATLAB 1.10 26 March, 2002

Page 11: MATLAB 1 - Introduction

ans = 23.14069263277927>> vpa(exp(1)^pi)ans =23.140692632779273907317474368028>> vpa('exp(1)^pi')ans =23.140692632779269005729086367949>> vpa('exp(1)^pi',50)ans =23.140692632779269005729086367948547380266106242601

Notice the use of the single quotes in the final two expressions. This syntax is

essential to obtain the required accuracy. Without them, as in vpa(exp(1)^pi),

MATLAB calculates exp(1) and pi separately, to about 16 digits, then performs the

operation.

We can perform calculations to any prescribed precision. MATLAB’s vpa command

has a default precision of 32 digits, however we can prescribe the number of digits as

in the following example in which we shall calculate :>> exp(1)^pians = 23.1407>> format long>> exp(1)^pians = 23.14069263277927>> vpa(exp(1)^pi)ans =23.140692632779273907317474368028>> vpa('exp(1)^pi')ans =23.140692632779269005729086367949>> vpa('exp(1)^pi',50)ans =23.140692632779269005729086367948547380266106242601

Notice the use of the single quotes in the final two expressions. This syntax is

essential to obtain the required accuracy. Without them, as in vpa(exp(1)^pi),

MATLAB calculates exp(1) and pi separately, to about 16 digits, then performs the

operation.

MATLAB 1.11 26 March, 2002

Page 12: MATLAB 1 - Introduction

1.11 Algebraic simplification

(i)

>> expand((a+b)^6)

ans =a^6+6*a^5*b+15*a^4*b^2+20*a^3*b^3+15*a^2*b^4+6*a*b^5+b^6>> factor(ans)ans =(a+b)^6

(ii) >> expand(exp(x+y))ans =exp(x)*exp(y)

(iii)

>> syms u v w>> collect((u+v+w)*(u-v-w))ans =-w^2-2*v*w+(u+v)*(u-v)>> collect((u+v+w)*(u-v-w),v)ans =-v^2-2*v*w+(u+w)*(u-w)>> collect((u+v+w)*(u-v-w),u)ans =u^2+(v+w)*(-v-w)>> expand(ans)ans =u^2-v^2-2*v*w-w^2

(iv) >> factor(u^2+2*v*u+v^2-w^2)ans =(u+v+w)*(u+v-w)

(v)

>> syms x

MATLAB 1.12 26 March, 2002

Page 13: MATLAB 1 - Introduction

>> simplify(3*cos(4*x)^2+3*sin(4*x)^2)ans =3

(vi)

>> syms x>> simplify(exp(-3*log(x)+1))ans =1/x^3*exp(1)

(vii) there are two commands for simplification, simplify and

simple:>> simplify(cos(x)+sqrt((-sin(x))^2))ans =cos(x)+csgn(sin(x))*sin(x)>> simple(cos(x)+sqrt((-sin(x))^2))simplify:cos(x)+csgn(sin(x))*sin(x)radsimp:cos(x)+sin(x)combine(trig):cos(x)+1/2*(2-2*cos(2*x))^(1/2)factor:cos(x)+(sin(x)^2)^(1/2)expand:cos(x)+(sin(x)^2)^(1/2)combine:cos(x)+1/2*(2-2*cos(2*x))^(1/2)convert(exp):1/2*exp(i*x)+1/2/exp(i*x)+(-1/4*(exp(i*x)-1/exp(i*x))^2)^(1/2)convert(sincos):cos(x)+(sin(x)^2)^(1/2)convert(tan):(1-tan(1/2*x)^2)/(1+tan(1/2*x)^2)+4^(1/2)*(tan(1/2*x)^2/(1+tan(1/2*x)^2)^2)^(1/2)collect(x):cos(x)+(sin(x)^2)^(1/2)ans =

MATLAB 1.13 26 March, 2002

Page 14: MATLAB 1 - Introduction

cos(x)+sin(x)

(viii) Substitute

>> syms x>> subs(cos(x), x, pi/4)ans = 0.7071>> subs(cos(x), x, sym(pi)/4)ans =1/2*2^(1/2)

(ix) Factorisation of 4248 and 4549319348597>> factor(4248)ans = 2 2 2 3 3 59>> factor(sym('4248'))ans =(2)^3*(3)^2*(59)

So we have the prime factors 2,2,2,3,3,59 and we can write .

>> factor(sym(4549319348597))ans =(4549319348597)

So we see that 4549319348597 is prime.

MATLAB 1.14 26 March, 2002

Page 15: MATLAB 1 - Introduction

1.12 Solution of equationsMATLAB can solve linear and non-linear equations in one or more variables. For

systems of linear equations see MATLAB file 5, matrices.

Equations with one variable

We write the equation in the form and use the solve command.

(i)>> syms x % we must ensure that x is defined symbolic>> solve(x^2+3*x-1)ans =[ -3/2+1/2*13^(1/2)][ -3/2-1/2*13^(1/2)]

so the result is

N.B. MATLAB returns a symbolic value. We can obtain a numerical value as

follows:>> double(ans)ans = 0.3028 -3.3028

(ii)>> solve(sin(x)+cot(x))ans =[ atan(1/2*(-2+2*5^(1/2))^(1/2)/(-1/2*5^(1/2)+1/2))+pi][ -atan(1/2*(-2+2*5^(1/2))^(1/2)/(-1/2*5^(1/2)+1/2))-pi][ atan(1/2*(-2-2*5^(1/2))^(1/2),1/2+1/2*5^(1/2))][ atan(-1/2*(-2-2*5^(1/2))^(1/2),1/2+1/2*5^(1/2))]>> double(ans)ans = 2.2370 -2.2370 0 + 1.0613i 0 - 1.0613i

(iii)

>> syms t>> solve(exp(t)-sqrt(t)-3)ans =1.4345424397933282359012271632074

MATLAB 1.15 26 March, 2002

Page 16: MATLAB 1 - Introduction

MATLAB can not find a symbolic solution and so finds a numerical solution correct

to 32 digits.

(v)>> syms x a>> solve(x^2+a*x+3)ans =[ -1/2*a+1/2*(a^2-12)^(1/2)][ -1/2*a-1/2*(a^2-12)^(1/2)]

so the solution is

MATLAB chooses x to be the variable and finds the solution in terms of a. Compare

this with>> syms x a>> solve(x^2+a*x+3,a)ans =-(x^2+3)/x

(vi)

>> clear all>> syms x a>> solve(exp(a*x)-sqrt(a+x)+1)Warning: Explicit solution could not be found.> In C:\MATLABR12\toolbox\symbolic\solve.m at line 136 In C:\MATLABR12\toolbox\symbolic\@sym\solve.m at line 49ans =[ empty sym ]

MATLAB can’t do everything!

Equations with two variables

(i)

We write the equations as strings, , then use solve.>> syms x y>> s1='x^2+y^2-2', s2='x+y-1's1 =x^2+y^2-2s2 =x+y-1>> [x, y]=solve(s1, s2)x =

MATLAB 1.16 26 March, 2002

Page 17: MATLAB 1 - Introduction

[ 1/2-1/2*3^(1/2)][ 1/2+1/2*3^(1/2)]y =[ 1/2+1/2*3^(1/2)][ 1/2-1/2*3^(1/2)]

so the solution is

>> double([x, y])ans = -0.3660 1.3660 1.3660 -0.3660

(ii)

>> syms x y a>> s1='x^2+y^2-a', s2='x+y-3*a+1's1 =x^2+y^2-as2 =x+y-3*a+1>> [x, y]=solve(s1, s2)x =[ -1/2+3/2*a-1/2*(-1+8*a-9*a^2)^(1/2)][ -1/2+3/2*a+1/2*(-1+8*a-9*a^2)^(1/2)]y =[ -1/2+3/2*a+1/2*(-1+8*a-9*a^2)^(1/2)][ -1/2+3/2*a-1/2*(-1+8*a-9*a^2)^(1/2)]

(iii)

>> clear all % a good idea to do this occasionally>> syms x y>> s1='exp(-x^2-2*y^2)-x', s2='x-y+1's1 =exp(-x^2-2*y^2)-xs2 =x-y+1>> [x, y]=solve(s1, s2)x =.91519355129007895766855983900894e-1y =1.0915193551290078957668559839009

MATLAB 1.17 26 March, 2002

Page 18: MATLAB 1 - Introduction

1.13 Partial fractions

For the expression MATLAB returns the partial fraction expansion

as .

Consider :

>> format rational % results as rational numbers>> b=[3,-8,-63]; a=[1,-3,-10]; [r,p,k]=residue(b,a)r = -4 5 p = 5 -2 k = 3

so that

1.12 Complex numbers

(i)>>format short>> z=1-2*jz = 1.0000 - 2.0000i>> real(z), imag(z) % real and imaginary partsans = 1ans = -2>> abs(z) % modulusans = 2.2361>> angle(z) % argument in radiansans = -1.1071

MATLAB 1.18 26 March, 2002

Page 19: MATLAB 1 - Introduction

(ii)

>> z=(2-j)*(5+3j)z = 13.0000 + 1.0000i

(iii)

>> z=exp(-j*pi/4)z = 0.7071 - 0.7071i

(iv) Solve the cubic equation >> solve('x^3-2*x^2+2*x-1=0')ans =[ 1][ 1/2-1/2*i*3^(1/2)][ 1/2+1/2*i*3^(1/2)]>> double(ans) % floating point formans = 1.0000 0.5000 - 0.8660i 0.5000 + 0.8660i

1.14 Partial fractions

For the expression MATLAB returns the partial fraction expansion

as .

Consider :

>> format rational % results as rational numbers>> b=[3,-8,-63]; a=[1,-3,-10]; [r,p,k]=residue(b,a)r = -4 5 p = 5 -2 k = 3

MATLAB 1.19 26 March, 2002

Page 20: MATLAB 1 - Introduction

so that

1.12 Complex numbers

(i)>>format short>> z=1-2*jz = 1.0000 - 2.0000i>> real(z), imag(z) % real and imaginary partsans = 1ans = -2>> abs(z) % modulusans = 2.2361>> angle(z) % argument in radiansans = -1.1071

(ii)

>> z=(2-j)*(5+3j)z = 13.0000 + 1.0000i

(iii)

>> z=exp(-j*pi/4)z = 0.7071 - 0.7071i

(iv) Solve the cubic equation >> solve('x^3-2*x^2+2*x-1=0')ans =[ 1][ 1/2-1/2*i*3^(1/2)][ 1/2+1/2*i*3^(1/2)]>> double(ans) % floating point formans = 1.0000

MATLAB 1.20 26 March, 2002

Page 21: MATLAB 1 - Introduction

0.5000 - 0.8660i 0.5000 + 0.8660i

1.15 BibliographyBorse GJ (1997) Numerical methods with MATLAB: a resource for scientists and

engineers, PWS Publishing. A good source of m-files for numerical applications.

Much of the material is advanced.

Dabney JB and Harman TL (2001) Mastering Simulink 4, Prentice Hall. An

excellent introduction to Simulink.

Hanselman D and Littlefield B (2001) Mastering MATLAB 6, Prentice Hall. An

advanced but very good reference text.

Higham DJ and Higham NJ (2000) MATLAB Guide, Siam. A mathematical, and

rather advanced, approach to MATLAB.

Hunt BR, Lipsman RL and Rosenberg JM (2001) A guide to MATLAB for beginners

and experienced users, Cambridge University Press. A very good introductory

text. It includes an introductory chapter on Simulink.

Kermit S and Davis TA (2002) MATLAB Primer, Chapman and Hall/CRC Press.

This small handbook is an ideal companion; it contains all you need to know

about MATLAB.

Kharab A and Guenther RB (2002) An introduction to numerical methods, a

MATLAB approach. A mathematical and fairly advanced text.

Marchand P (1999) Graphics and GUIs with MATLAB, CRC Press. An advanced

but very good text for graphics.

MATLAB 1.21 26 March, 2002