Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes...

22
Introduction to Matlab September 17, 2012 Contents 1 Application MATLAB 2 1.1 Description of windows ................................ 2 1.2 The work directory .................................. 3 1.3 Set Path ........................................ 3 1.4 Icons of the window Editor ............................. 4 1.5 Subprograms ..................................... 5 1.6 Manipulation with data ............................... 6 2 Introduction to programming in the Matlab language 7 2.1 Introductory notes .................................. 7 2.2 Variables and operations ............................... 7 2.3 Programming commands ............................... 9 2.4 Printing the output .................................. 10 2.5 Displaying graphic output .............................. 11 3 Examples of programs in MATLAB 13 1

Transcript of Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes...

Page 1: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

Introduction to Matlab

September 17, 2012

Contents

1 Application MATLAB 2

1.1 Description of windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.2 The work directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.3 Set Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

1.4 Icons of the window Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.5 Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.6 Manipulation with data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Introduction to programming in the Matlab language 7

2.1 Introductory notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2 Variables and operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.3 Programming commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.4 Printing the output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.5 Displaying graphic output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3 Examples of programs in MATLAB 13

1

Page 2: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

1 Application MATLAB

MATLAB is a professional interactive system for technical computations. It is made andfurther developed by the company The MathWorks, Inc. and it is protected by U.S. patents.Our school has legally bought it and students can download it and use it at home. It isnecessary to be constantly connected to the Internet. It is possible to download it on thisaddress:

https://download.cvut.cz/info/info.php?id=173

which of course needs to login.

After launching the program MATLAB it appears an integrated window of the application:

1.1 Description of windows

There is a window Current folder on the left side of the application. There we can see displayedsubfolders and files of the active directory which has been chosen and displayed in the whitewindow in the upper strip of icons.

2

Page 3: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

In the middle part there is situated a window Editor which serves for editing and startingprograms. Below it there is a window called Command window in which it is possible to entercommands interactively and to display results of programs which have been launched fromEditor.

We can open a window with values of variables in Workspace on the right side of the applica-tion. There is an editor of variables called Variable editor below it which enables to enter orto repair complicated variables such as structures or cell-vectors.

It is possible to activate or hide windows from menu Desktop, or directly with the help of themouse. For moving a window it is enough to take it by its bar (mostly it is inclusive icons)and to drag. It appears a box which skips item by item. At the moment we are satisfied withits position we drop the window and its position is fixed. As well the window can be take outfrom the integrated area by clicking on an arrow turned askew up in the right part of the iconbar. After taking out the arrow turns askew down and the window is possible to insert to theapplication again (to dock).

1.2 The work directory

Matlab works with a so called work directory. Results are automatically saved to this directory.Matlab searches for called files in this directory at first as well. The content of the workdirectory (subfolders respectively) is shown in the window Current folder.

Settings of the work directory are possible to accomplish with the help of icons above theeditor, see the picture:

To find a directory it is sufficient to use the white window. There are saved directories whichhave been lastly used. From there it is possible to call again the lastly used directories as well.In case we still have a directory that has not been used yet, we can get to it by using the iconnext to this white window (the icon with 3 dots). This icon opens the whole directory tree.

1.3 Set Path

To use files that are not in the current work directory it is necessary to set them to Path,which serves Matlab to find these called files. It is possible to make it by clicking on the menuFile on the item Set Path. After its choice the dialog box opens:

3

Page 4: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

Directories can be added thanks to the buttons Add Folder (it adds just one directory) andAdd with Subfolders (it adds a directory inclusive its subfolders). Directories can be eliminatedby the button Remove.

Important! Before closing the window it is necessary to save the added path. If it is notsaved, settings are valid till Matlab is opened.

1.4 Icons of the window Editor

For launching and debugging programs icons in the window Editor are important. These iconsare illustrated on the next picture (they are numbered for links):

Work in the application MATLAB

As it has been mentioned, there are two ways of work in Matlab.

• Interactive - it works just in the window Command window, where commands areentered (there is only one command line used). The answer is promptly obtained afterapproving thanks to the button Enter (if there is no semicolon behind a command or ifa command gives a result).

X If the entered command is not matched with a variable, its value is matched witha general variable ans. Later it is possible to call the calculated value under thisgeneral variable.

X The lastly entered command (and then older ones) can be called up by the key ↑.Then it can be edited.

4

Page 5: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

• Batch - particular commands are written like a program to the Editor. The commandsare then launched at the same time. The program can be launched by the icon 12.

X Results can be obtained in three different ways: (i) by printing or by a graph fromthe program, (ii) by asking about a variable after finishing the process, (iii) byobserving the result in the window Workspace (a variable is copied to the windowVariable editor by double click, it is possible to view complicated variables as well).

X If the program does not run correctly, it announces an error in Command window.A place and a cause of the error are written in an error list. This report is veryuseful.

X If we are not able to determine the error(s) from the error list, we have the oppor-tunity to step the program. By the mouse we label the place where the programshould be after launching stopped on, so that we click on the dash (-) by the cor-responding number of the row. It appears a big dot (if the program is not saved,it has the green color, if it is, it has the red color). The stopped program can bestepped by the icon 15. If we want to enter the subprogram by stepping, we usethe icon 16. To stop stepping it has to be used the icon 19.

1.5 Subprograms

There is possible to use standard (contained in Matlab) or one’s own subprograms in programsof language MATLAB.

Matlab contains a great number of its own functions. Its overview can be displayed by enteringthe command help in Command window. It appears a list of fields of functions with a shortdescription to be clicked on. It can be searched in it deeply. It is possible to ask about theconcrete function by the command help name (for example help plot). The help of Matlabwhich can be called by the click on the icon help (the blue circle with a question mark inthe upper row of icons) can be used. Here it can be found besides instructions a group ofexamples of using functions.

Particular subprograms are written like a separate program file with a name of the file andthe ending .m. They are called by the name without the ending. They are of two characters:

• The script - a group of commands which are saved separately. The name of the file isinserted to our program to a place. From this place the commands are easily called asif they are written there.

• The function - a group of commands which are separately saved inclusive of a headerwith formal input and output parameters. It is called by real parameters, which arepassed on to formal ones according to an order.Note:A notation and use of functions in Matlab are similar to other common programminglanguages. Variable functions are local. Values of these functions are given back throughoutput parameters.

5

Page 6: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

An example of notation of a function

function [m1,m2,v1,v2,co] = moments(x,y)

% [mx,my,vx,vy,co] = moments(x,y)

% first and second moments of an universe x, y

% mx,my first moments (mean)

% vx,vy second moments (variance)

% co second mutual moment(covariance)

% x,y data universe (sample)

mx=mean(x);

my=mean(y);

vx=var(x);

vy=var(y);

co=cov(x,y);

An example of using the function

x = [1 2 2 3 2 3 1 1];y = [3 5 2 6 1 2 6 3];[meanX, meanY, varX, varY, covXY] = moments(x,y)

1.6 Manipulation with data

Data has two forms in Matlab - input data (which we want to adapt) and data computed inthe program. Both forms of data can be downloaded to a memory of a computer, or contrarilyit can be saved to a disc by the help of the command load or save. The most common syntaxis following:

command meaning

load name the file name.mat is being called in the format of Matlabload name.end the file name.end is being calledload -ascii name the file in text format (ascii) is being calledsave name the file name.mat is being saved in the format of Matlabsave name.end the file name.end is being savedsave -ascii name the file in text format (ascii) is being saved

6

Page 7: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

2 Introduction to programming in the Matlab language

2.1 Introductory notes

1. All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector can be aline a(1,5), or a column a(5,1).

2. A semicolon behind an entered variable a=5; causes no response after entering. Con-versely there is a variable written on the screen when it is entered with a comma orwithout anything - a=5, or a=5.

3. help”object“ displays the help for the demanded object.

The icon ? calls an interactive side HELP.

4. Comments are texts which begin by %. They are not important in computations ofprograms.

5. Commands are possible to put to a text file with the ending .m (batch-file) and to launchthem by calling the name of the file in the main program (see 1/Work in the applicationMatlab).

2.2 Variables and operations

Types of variables

Subsequently main types of variables, which we work with, are mentioned. They are just asmall fraction from the existing set of variables.

• string serves for a notation of a text: a=’hello’. Strings can be joined to vectors: ifa=’good ’; b=’morning’ and c=[a,b], then c=’good morning’. As well the conversionnumber → string is very useful: s=num2str(a), where s is of the type string and a

double.

• double serves for inherent or for real variables. Their definition can be executed infollowing way:

By entering a value:- a scalar a=5;- a row vector a=[3 5 1];- a column vector a=[3; 5; 1], which is the same like a=[3 5 1]’- a matrix a=[2 3 4; 8 7 6];

• Elements of vectors or matrices are entered to square brackets.

• Elements of rows are separated by the comma or by the space.

• The semicolon ends a row of a matrix and goes to another row.

7

Page 8: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

• A transposition is executed by the apostrophe ’.

By the colon:- a=5:8 with the increment 1 makes the vector [5 6 7 8]

- a=2:3:10 with the increment 3 makes the vector [2 5 8]

By a function- a=zeros(2,3) makes a matrix 2 x 3 of zeros

- a=ones(2,3) makes a matrix 2 x 3 of ones

Operations with variables

• A selection of elements of a matrix:a(3:5) a list of 3rd,4th a 5th element of the vector a.a(:,1) a list of 1st column of the matrix a

a(2:3,:) a list of 2nd and 3rd row of the matrix a.

• Operations: + - ∗ / ˆa+b a a-b ... addition and subtraction (these operations can be done just for thesame dimensions of a and b)a*b ... multiplication (one has to pay attention on correct dimensions by multiplicationof matrixes, respectively of vectors)a/b or a\b ... a times inversion of b, or inversion of a times b

ˆ... raising, a=sqrt(b) ... extracting of functions

• Dot operations: .∗ ./ .̂They mean operations

”element after element“. For example:

[1 2 3].*[6 5 4] means [1*6 2*5 3*4][2 3; 4 1].̂ [5 3; 2 8] means [2̂ 5 3̂ 3; 4̂ 2 1̂ 8]

• Operations with a matrix and a scalar: + - * / ˆFor matrices a scalar is valid for all elements of the matrix.:[2 3]*4 je [2*4 3*4]

• Logical operations:== ∼= < <= > >= & (=and) | (=or) ∼ (=not)

Work with variables

• Commands who, whos give information about defined variables.

• [m,n]=size(a), m=size(a,1), n=size(a,2) give information about dimensions of the matrixa, respectively about number of rows, respectively about number of columns.

• n=length(a) give information about a length of a vector, respectively a larger dimensionof the matrix a.

• clear, clear all releases the memory .

8

Page 9: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

2.3 Programming commands

• The condition if

if b>c,a=5;

elsea=0;

end

If the condition b>c holds , the command a=5; is executed else the command a=0; is valid.

• The multiple condition if

if b>1,a=5;

elseif b<-.1,a=-5;

elsea=0;

end

If the condition b>1 holds , the command a=5; is executed and the procedure ends. If thecondition b>1 does not hold, the second condition b<-1 is tested and either the commanda=-5; or a=0; is executed.

• The cycle for

for i=1:5a(i)=2*i;

end

For i=1,2,3,4,5 the command a(i)=2*i;is executed. The result is: a=[2, 4, 6, 8, 10].

• The cycle while

while i<=5a(i)=0;i=i+1;

end

While the condition i≤5 is being fulfiled, the commands a(i)=0; a i=i+1; are executed, wherei is an increment. The result is: a=[0, 0, 0, 0, 0].

• Clc, clear, clear all, clear functions

Clc deletes everything in the Command window.

Clear deletes data in the memory.

Clear all deletes all memory except for downloaded functions.

Clear functions deletes functions in the memory.

9

Page 10: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

• Close, close all

Close closes an active window of a graph.

Close all closes all windows with graphs.

• Break, return

Break causes finishing of the cycles for or while. A program continues behind the cycles.

Return causes finishing of an executing procedure.

• Pause, keyboard, input

Pause causes stopping of a program. The program continues after pushing any key.

Keyboard causes stopping of a program and transfers control to a keyboard - it is possibleto check variables inside a program (it continues after entering the command exit).

Input causes stopping of a program and it waits for an input of a variable (it needs tobe entered and confirmed by Enter).

E.g.: a=input(’Enter the value a: ’); writes a text in apostrophes and the entered valueassigns to the variable a.

• Eval

Eval(string) launches a command which is written in the variable string.

E.g.eval(’x=1;’) gives the command x=1 oreval([’x’,num2str(i),’=1;’]) for i=5 gives x5=1.

• Setting of seed for a random generatorRand(’seed’,number) - the choice seed is used for generating of a pseudo-random real-ization of numbers (it generates random numbers but with the same realization in eachoperation). Number is long odd integer - e.g. 135731.

2.4 Printing the output

The commands disp (without a format) and fprintf (with a format) serve for a print ofvariables.

• disp(a) displayes a value of the variable a.

• disp(’hello’) writes the text hello.

• fprintf(’element %g of the vector a is %g\n’,i,a(i));writes: element 5 of the vector a is 4.12 (if it is true).

10

Page 11: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

2.5 Displaying graphic output

A two-dimensional graph is possible to draw by the command plot.

Examples:

• plot(y) draws values of the vector y. There is an order of the vector (an index) on theaxis x.

• plot(x,y) draws values of the vector y against values of the vector x – so called thexy-graph.

• plot(a) draws columns of the matrix a.

Formatting a graph:

Types of a line Types of a point Colour- (solid) . (point) r (red): (dotted) + (plus) g (green)-. (dot-and-dash) o (circle) b (blue)– (dashed) x (cross) w (white)

Other possibilities: help plot.

Examples:

• plot(x,’or’) draws the vector x using red circles.

• plot(x,y,’r-+’,u,v,’b-x’) draws two curves (x,y) and (u,v); the first one using red solid linewith pluses, the second one using blue solid line with crosses.

A three-dimensional graph (entered by a matrix of points) is possible to draw by thecommand mesh.The function meshgrid prepares arguments for a computation of a displayed matrix.

The following program draws an unnormalized probability density of normal distribution.

x=-1.9:.1:2; y=x’; sig=.6;[xx yy]=meshgrid(x,y);z=1/sig*exp(-.5/sigˆ2*(xx.ˆ2+yy.ˆ2));mesh(x,y,z);

11

Page 12: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

12

Page 13: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

3 Examples of programs in MATLAB

% clc , c l e a r a l l%% %% MATCHING A VALUE WITH A VARIABLE% % − the semico lon suppre s s e s a prompt statement o f a va lue% % − a d i s p l a y o f a va lue − one has to wr i t e a va lue without the semico lon% % − a text v a r i a b l e works l i k e a vec to r o f l e t t e r s%% a=5; % the value i s 5 ; the value w i l l not be d ip layed%% b=[3 2 5 ] % ent e r i ng o f va lue s o f a ( row ) vec to r%% c =[2 1 3 ] ’ % ent e r i ng o f va lue s o f a ( column ) vec to r% d = [ 2 ; 1 ; 3 ] % the same statement − j u s t by us ing semico lons%% e =[3 4 ;5 6 ; 7 8 ] % the matrix 3x2%% f =[c e ] % a connect ion o f matr ixes c and e − they have to have the c o r r e c t dimensions% g=[b c ’ d ’ ] % another way how to connect matr ixes%% h=f ( : ) % g iv ing the matrix f to the vec to r h ( accord ing to columns )%% i=f ( : , 1 : 2 ) % a cho i c e o f a submatrix − 1 :K=[1 2 3 . . K]% j=g ( [ 3 : 5 6 8 ] ) % a cho i c e o f subvector s%% k=’Navod ’ % text v a r i a b l e s% l =’Matlab ’% m=[k , ’ k ’ , l , ’ u ’ ] % a connect ion o f t ex t v a r i a b l e s ( l i k e ve c to r s )%% o=ze ro s (1 , 5 ) % genera t ing the vec to r 1x5 from ze ro s − i t i s used l i k e a d e c l a r a t i o n% p=ones (3 , 4 ) % genera t ing the matrix 3x4 from ones% q=rand (1 ,20 ) % genera t iong the vec to r with uni formly d i s t r i b u t e d random numbers% r=randn (12 ,2 ) % genera t iong the vec to r with normaly d i s t r i b u t e d random numbers%% %% OPERATIONS WITH VARIABLES%% 3∗a % s c a l a r m u l t i p l i c a t i o n% 3∗b % m u l t i p l i c a t i o n o f the vec to r b by the s c a l a r 3% aˆ2 % r a i s i n g to the power o f two ( squar ing )%%% b∗c % m u l t i p l i c a t i o n o f v e c t o r s − . | ( the r e s u l t i s a number )% b ’∗ c ’ % m u l t i p l i c a t i o n o f v e c t o r s | .− ( the r e s u l t i s a matrix )% b .∗ c ’ % m u l t i p l i c a t i o n element by element% e ∗ [ b ; c ’ ] % m u l t i p l i c a t i o n o f matr ixes

13

Page 14: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% b .ˆ2 % squar ing a l l the e lements o f the vec to r b% b . ˆ [ 2 3 4 ] % r a i s i n g to the power o f two , three and four%% %% COMMANDS%% % the cond i t i on i f% c lc , c l e a r a l l% s=randn % genera t ing a random number s% i f s>0% t =’ p o s i t i v e ’ ; % p o s i t i v e va lue o f the generated number% e l s e% t =’ negat ive ’ ; % negat ive va lue o f the generated number% end% disp ( [ ’ the generated number i s ’ , t ] ) % pr i n t o f the t e s t e d number%% % the c y c l e f o r% c lc , c l e a r a l l% a = [ ] ; % a d e c l a r a t i o n by an empty matrix% f o r i =1:5 % genera t ing numbers 1 ,2 ,3 ,4 ,5% a=[a 1/ i ] ; % a t r i c k : i t i s added to an empty matrix% end% a % p r in t o f the r e s u l t − di sp ( a ) can be used as we l l%% % the c y c l e whi l e% % y=s q r t ( x ) − a lgor i thm : y(0)=x% % y ( i +1)=.5∗(x/y ( i )+y ( i ) )% c lc , c l e a r a l l% x=91; % an i n i t i a l i z a t i o n o f the a lgor i thm −> r e s p e c t i v e l y o f v a r i a b l e s% t e s t =1; y=x ; n=0;% whi le t e s t >1e−5 % the c y c l e ( i f the r equ i r ed accuracy i s not reached )% n=n+1; % a counter o f i t e r a t i o n s% yn=.5∗(x/y+y ) ; % the r e a l a lgor ithm , r e s p e c t i v e l y the computation o f yn% t e s t=abs (yn−y ) ; % the t e s t o f the accuracy between y and yn% y=yn ; % the new one −> the o ld one% end% disp ( ’ the r e s u l t ’ ) % p r i n t i n g o f the r e s u l t% disp ( y )% disp ( ’ number o f i t e r a t i o n s ’ )% disp (n)%% %% GENERATING RANDOM NUMBERS − var i ous types o f a d i s t r i b u t i o n%% % normal = add i t i on o f s i x uniform d i s t r i b u t i o n s on the i n t e r v a l ( − . 5 , . 5 )% c lc , c l e a r a l l% x=sum( rand (6 ,1000) − . 5 ) ; % sum adds up a matrix a f t e r columns% % rand−.5 i s uniform on (−0.5 , 0 . 5 )

14

Page 15: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% f i g u r e ( 1 ) , h i s t (x , 2 0 ) % a histogram (20 i n t e r v a l s )% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the normal d i s t r i b u t i o n ’ )%% % ch i ˆ2 = add i t i on o f squares o f normal d i s t r i b u t i o n% c lc , c l e a r a l l% x=sum( randn ( 5 , 1 0 0 0 ) . ˆ 2 ) % a dot opera t i on = f o r each element% f i g u r e ( 2 ) , h i s t (x , 2 0 )% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the ch i ˆ2 d i s t r i b u t i o n ’ )%% % student = normal/ ch i ˆ2% c lc , c l e a r a l l% x=sum( randn ( 5 , 1 0 0 0 ) . ˆ 2 )% y=randn ( 1 , 1 0 0 0 ) . / x ;% f i g u r e ( 3 ) , h i s t (y , 2 0 )% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the student d i s t r i b u t i o n ’ )%%% % a l t e r n a t i v e with p i =.3% c lc , c l e a r a l l% x=rand (1 ,1000) < . 3 ; %% y=h i s t (x , 2 ) ; %% f i g u r e ( 4 ) , bar ( [ 0 1 ] , y /1000 , . 5 ) %% a x i s ([−1 2 0 1 ] ) % s e t t i n g o f the a x i s o f a graph% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the a l t e r n a t i v e d i s t r i b u t i o n ’ )%% % mult inomial% c lc , c l e a r a l l% p = [ . 2 . 1 . 1 . 3 . 3 ] ; % p r o b a b i l i t i e s o f p a r t i c u l a r va lue s% pp=cumsum(p) % cumulat ive add i t i on o f p r o b a b i l i t i e s% x=ze ro s ( 1 , 1 0 0 0 ) ; % a d e c l a r a t i o n% f o r i =1:1000 % repea t ing the experiment% x ( i )=sum( rand>pp)+1; % example : .451 > [ . 2 . 3 . 4 . 7 1 ]=[0 0 0 1 1 ]% end% a=h i s t (x , l ength (p ) )% f i g u r e ( 5 ) , bar ( 1 : l ength (p ) , a /1000)% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the mult inomial d i t r i b u t i o n ’ )%% % binomial% c lc , c l e a r a l l% p=.3; n=10; nd=1000; % the p robab i l i t y , number o f t r i a l s , number o f exper iments% f o r i =1:nd % repea t ing the experiment% x ( i )=sum( rand (1 , n)<p ) ; %% end% a=h i s t (x , 0 : n ) ;% f i g u r e ( 6 ) , bar ( 0 : n , a/nd)% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the binomial d i s t r i b u t i o n ’ )

15

Page 16: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

%% % geomet r i ca l% c lc , c l e a r a l l% p=.3; nd=1000; % the p robab i l i t y , number o f exper iments% x=ze ro s (1 , nd ) ;% f o r i =1:nd % repea t ing the experiment% j =0;% r=rand<p ; % the a l t e r n a t i v e p r o b a b i l i t y ( the f i r s t s tep )% whi le r==0% j=j +1;% r=rand<p ; % the a l t e r n a t i v e p r o b a b i l i t y ( in the p rog r e s s )% end% x ( i )= j ; % sav ing o f the r e s u l t% end% xx=max( x ) ;% a=h i s t (x , 0 : xx ) ;% f i g u r e ( 7 ) , bar ( 0 : xx , a/nd)% t i t l e ( ’ The p r o b a b i l i t y dens i ty o f the geomet r i ca l d i s t r i b u t i o n ’ )%%% %% EXAMPLES ON THE STATISTICAL PROBABILITY%% % What ’ s the value o f the p r o b a b i l i t y provided that by a t o s s o f two co in s% % the same s i d e f a l l s ?% c lc , c l e a r a l l% nd=100000; % number o f t o s s e s% m1=rand (1 , nd ) < .5 ; % genera t ing a t o s s o f the f i r s t co in with the p robab i l i t y <0,5% m2=rand (1 , nd ) < .5 ; % genera t ing a t o s s o f the second co in with the p robab i l i t y <0,5% n1=sum(m1==m2) ; % the same va lue s o f the p r o b a b i l i t y ?% P=n1/nd % the computed p r o b a b i l i t y%% % There are 3 white and 5 blue beads in a hat . One by one , without g i v ing% % back , we take out 2 beads . What ’ s the value o f the p robab i l i t y , that the% % second bead i s white ?% c lc , c l e a r a l l% Pb=3/8; % the t h e o r e t i c a l p r o b a b i l i t y o f a cho i c e o f the white bead% nd=1000; % number o f exer iments% n1=0;% f o r i =1:nd % repea t ing the experiment% i f rand<Pb% Pb=2/7; % the p r o b a b i l i t y ( white | the f i r s t white ) in the second cho i c e% e l s e% Pb=3/7; % the p r o b a b i l i t y ( white | the f i r s t b lue ) in the second cho i c e% end% i f rand<Pb% n1=n1+1; % when the second one i s white

16

Page 17: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% end% end% P2b=n1/nd % the p r o b a b i l i t y got from the exper iments% f p r i n t f ( ’ the s t a t i s t i c a l p r o b a b i l i t y from %d exper iments i s %g\n ’ , nd , P2b)% f p r i n t f ( ’ the t h e o r e t i c a l p r o b a b i l i t y i s %g\n ’ , 3 / 8 )%% % We are throwing two d i c e s . What ’ s the value o f the p robab i l i t y , that the sum i s even ,% % i f we know :% % ( i ) On the f i r s t d i c e the s i x did not f a l l ?% % ( i i ) The s i x did not f a l l on any d i c e ?% nd=1000;% disp ( ’ The task ( i ) ’ )% % −−−−−−−−−−− the task ( i )% K1=f i x (5∗ rand (1 , nd ))+1; % the f i r s t d i c e ( without the s i x )% K2=f i x (6∗ rand (1 , nd ))+1; % the second d i c e ( i n c l u s i v e the s i x )% s=K1+K2 ; % the sum of p r o b a b i l i t i e s o f both d i c e s% n1=sum( f i x ( s/2)∗2==s ) ; % the t e s t f o r an even number ( f i x removes the f r a c i t i o n a l part )% Ps1=n1/nd ; % the computed p r o b a b i l i t y% f p r i n t f ( ’ the s t a t i s t i c a l p r o b a b i l i t y o f the even sum i s %g\n ’ , Ps1 )% f p r i n t f ( ’ the t h e o r e t i c a l p r o b a b i l i t y o f the even sum i s %g\n ’ , . 5 )% disp ( ’ ’ )% disp ( ’ The task ( i i ) ’ )% % −−−−−−−−−−−− the task ( i i )% K3=f i x (5∗ rand (1 , nd ))+1; % the second d i c e ( without the s i x )% s=K2+K3 ; % the sum of p r o b a b i l i t i e s o f both d i c e s% n1=sum( f i x ( s/2)∗2==s ) ; % the t e s t on an even number% Ps2=n1/nd ; % the computed p r o b a b i l i t y% f p r i n t f ( ’ the s t a t i s t i c a l p r o b a b i l i t y o f the even sum i s %g\n ’ , Ps2 )% f p r i n t f ( ’ the t h e o r e t i c a l p r o b a b i l i t y o f the even sum i s %g\n ’ , 13/25 )%% % There are n products in the s t o r e . Among a l l products m products are% % d e f e c t i v e . We choose 4 products to be checked . What ’ s the value o f the% % probab i l i t y , that the re are no , one up to four good products among the four checked ?% % −− a cho i c e a l l at once = without g i v ing back .% c lc , c l e a r a l l% nd=10000;% n=10; % number o f products in the s t o r e% m=4; % number o f d e f e c t i v e ones% nv=4; % the sample s i z e% x=[ z e ro s (1 ,m) ones (1 , n−m) ] ; % the products (0= d e f e c t i v e , 1=good )% d=ze ro s (1 , nv+1); % a d e f i n i t i o n o f a counter f o r good r e s u l t s% f o r i =1:nd % repea t ing the experiment% xp=x ; % a work vec to r o f the product% f o r k=1:nv % the cho i c e o f nv products without g i v ing back% nx=length ( xp ) ; % number o f remaining products in the s t o r e% j=f i x ( nx∗ rand )+1; % a random cho i c e o f the product ( i t s order )

17

Page 18: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% v ( k)=xp ( j ) ; % the chosen product% xp=xp ( [ 1 : j−1 j +1:nx ] ) ; % the r e s t o f the products ( without the chosen one )% end% k=sum( v ) ; % number o f good ones in the sample% d( k+1)=d( k+1)+1; % a counter o f a r e s u l t% end% disp ( ’ The cho i c e without g i v ing back ’ )% P1=d/nd % the s t a t i s t i c a l p r o b a b i l i t y%% % −− the cho i c e with g i v ing back% p=m/n ; % the p r o b a b i l i t y o f a good product ( s t i l l the same one )% c=ze ro s (1 , nv+1); % a d e f i n i t i o n o f a counter f o r good r e s u l t s% f o r i =1:nd % repea t ing o f the t r i a l% x=f i x ( rand (1 , nv)>p ) ; % the cho i c e o f the product with g i v ing back% k=sum( x ) ; % number o f good ones in the sample% c ( k+1)=c ( k+1)+1; % a counter o f a r e s u l t% end% disp ( ’ The cho i c e with g i v ing back ’ )% P2=c/nd % the s t a t i s t i c a l p r o b a b i l i t y%% % Ver i fy the v a l i d i t y o f the r e l a t i o n between a mean and a var iance o f a sample .% c lc , c l e a r a l l% nd=1000; % number o f r epea t ing o f the experiment% nx=100; % number o f data% n=50; % the sample s i z e% mi=5; % the mean o f the data genera to r% sg =10; % the standard dev i a t i on o f the data generato r% x=sg ∗ randn (1 , nx)+mi ; % the generated data% disp ( ’ The mean and the var iance o f the universe ’ )% mx=mean( x ) % the mean o f the data% s2x=var ( x ) % the var iance o f the data% f o r i =1:nd% v=vyber (n , x ) ; % the sampled data% mv=mean( v ) ; % the mean o f the sampled data% mm( i )=mv; % sav ing o f the mean o f the sampled data% end% disp ( ’ The mean and the var iance o f the sample ’ )% mmx=mean(mm) % the mean o f sample means% ss2x=var (mm) % the var iance o f sample means%%% % an a u x i l i a r y func t i on to the prev ious program% func t i on v=vyber (nv , x )% % v=vyber (nv , x ) a random sample o f nv e lements from the vec to r x without g i v ing back% v=ze ro s (1 , nv ) ;% f o r k=1:nv % the cho i c e o f nv e lements withou g iv ing back

18

Page 19: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% nx=length ( x ) ; % number o f remaining e lements in x% j=f i x ( nx∗ rand )+1; % the random cho i c e o f an element ( i t s order )% v ( k)=x ( j ) ; % the chosen element% x=x ( [ 1 : j−1 j +1:nx ] ) ; % the remaining e lements ( without the chosen one )% end%%% % Ver i fy the v a l i d i t y o f the c e n t r a l l i m i t theorem f o r a ba s i c un ive r s e% % with an a l t e r n a t i v e d i s t r i b u t i o n with the parameter p .%% clc , c l e a r a l l% nd=100000; % number o f r epea t ing the experiment% n=500; % the sample s i z e% p=.3; % the parameter p o f the a l t e r n a t i v e d i s t r i b u t i o n% nh=30; % number o f i n t e r v a l s f o r a histogram% x=ze ro s (1 , nd ) ;% f o r i =1:nd % repea t ing the t r i a l% s =0; % the computation o f the sample mean% f o r j =1:n% s=s+f i x ( rand < . 3 ) ;% end% s=s /n ; % the sample mean from the a l t e r n a t i v e d i s t r i b u t i o n% x ( i )=s ; % sav ing o f the sample mean% end% f i g u r e (1 )% [ f s ]= h i s t (x , nh ) ;% bar ( s , f )% t i t l e ( ’ The histogram of the sample means from the a l t e r n a t i v e d i s t r i b u t i o n ’ )%% %% GRAPH DRAWING%% % plo t − the ba s i c use% c lc , c l e a r a l l% nd=100; % max f o r an i n t e r v a l o f drawing% s = 0 : . 1 : nd ; % po in t s f o r drawing ( a f t e r tenths )% x=s i n ( s /nd∗4∗ pi ) ; % the func t i on x% y=2∗cos ( s ) . ∗ exp (−.05∗ s ) ; % the func t i on y% z=3∗ s i gn ( s i n ( s /nd∗3∗ pi ) ) ; % the func t i on z% f i g u r e (11)% p lo t ( s , x , ’ r ’ , s , y , ’ b ’ ) , hold on % the graph drawing (when there i s hold on −> everyth ing i s drawed to% p lo t ( s , z , ’ g ’ , ’ l inewidth ’ , 3 ) , hold o f f % the same p i c t u r e − i t i s cance l ed by hold o f f )% a x i s ( [ 1 nd −4 4 ] )% legend ( ’ s ine ’ , ’ damped cos ine ’ , ’ jumps ’ , 0 ) % a d e s c r i p t i o n o f curves ( a f t e r i t s order )%% % plo t − s e t t i n g s f o r fo rmatt ing a graph% c lc , c l e a r a l l

19

Page 20: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% nd=100;% s = . 1 : . 1 : nd ;% x=s ( 1 0 : 1 0 : nd ) ; % the func t i on x% y=s .∗ exp (−.05∗ s ) ; % the func t i on y% [my i ]=max( y ) ; % maximum of the func t i on (my) and i t s p o s i t i o n ( i )% mx=i /10 ; % the p o s i t i o n o f the maximum in r e a l un i t s%% % the graph and i t s fo rmatt ing% s e t ( f i g u r e ( 1 2 ) , ’ Pos i t ion ’ , [ 1 0 0 100 600 6 0 0 ] )% p lo t ( s , y,’−−r ’ ,mx,my, ’ o ’ , ’ MarkerEdgeColor ’ , ’ k ’ , ’ LineWidth ’ , 2 , . . .% ’ MarkerFaceColor ’ , ’ g ’ , ’ MarkerSize ’ , 1 0 )% t i t l e ( ’ The func t i on ’ ’ x∗exp(−x ) ’ ’ and i t s maximum’ , ’ FontSize ’ , 1 6 , . . .% ’FontName ’ , ’ Times ’ )% x l a b e l ( ’ Arguments ’ , ’ FontSize ’ , 1 4 , ’ FontName ’ , ’ Times ’ )% y l a b e l ( ’ The value funct ion ’ , ’ FontSize ’ , 1 4 , ’ FontName ’ , ’ Times ’ )% legend ( ’ the funct ion ’ , ’ the maximum’ , 0 )%% % plo t − another use% c lc , c l e a r a l l% nd=30.4∗ pi ; s = . 1 : . 1 : nd ; % number o f data , po in t s f o r drawing% a=5; b=10; h=.01; % a , b − ha l f−a x i s o f an e l l i p s e , h − a change o f ha l f−a x i s% x=ze ro s (1 , l ength ( s ) ) ; y=x ;% f o r i =1: l ength ( s )% x ( i )=a∗ s i n ( s ( i ) ) ; % x−coord ina te% y ( i )=b∗ cos ( s ( i ) ) ; % y−coord ina te% a=a+h ; b=b−h ; % the change o f ha l f−a x i s% end% f i g u r e (13)% p lo t (x , y )%% % 3D graphs% c lc , c l e a r a l l% f=@(x , y ) exp (−.01∗xˆ2−.03∗y ˆ 2 ) ; % a d e f i n i t i o n o f an anonymous func t i on% x=−10:10; y=−10:10; % l i m i t s f o r x and y% f o r i =1: l ength ( x )% f o r j =1: l ength ( y )% z ( i , j )= f ( x ( i ) , y ( j ) ) ; % a matrix o f va lue s o f the two−dimens iona l func t i on% end% end% s e t ( f i g u r e ( 1 4 ) , ’ po s i t i on ’ , [ 1 0 0 500 400 4 0 0 ] ) , mesh (x , y , z )% t i t l e ( ’ mesh ’ )% view (−132 ,62) % a format o f a graph ( turning , l ean )% s e t ( f i g u r e ( 1 5 ) , ’ po s i t i on ’ , [ 6 0 0 500 400 4 0 0 ] )% w a t e r f a l l (x , y , z )% t i t l e ( ’ w a t e r f a l l ’ )% s e t ( f i g u r e ( 1 6 ) , ’ po s i t i on ’ , [ 1 1 0 0 500 400 4 0 0 ] )

20

Page 21: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

% contour (x , y , z )% t i t l e ( ’ contour ’ )

%% WORK WITH VECTORS AND MATRIXES

% the l a r g e s t even element o f a vec to rc l c , c l e a r a l lnd=100; % number o f e lementsv=f i x (100∗ rand (1 , nd ) ) ; % an i n t e g e r from the i n t e r v a l (0 , 100)mx=−i n f ; % the l a r g e s t va lue − an i n i t i a l i z a t i o nf o r i =1:nd % the c y c l e o f g e t t i n g through numbers

i f v ( i )/2== f i x ( v ( i )/2) % f i n d i n g o f even numbersi f v ( i )>mx % i t i s found a l a r g e r even number then found so f a r

mx=v ( i ) ; % sav ing o f a numbermi=i ; % sav ing o f an order

endend

endf p r i n t f ( ’ The l a r g e s t va lue o f the even number i s %g .\n ’ ,mx)f p r i n t f ( ’ This va lue has been found on the %g th p lace .\n ’ , mi )

% orde r ing o f e lements o f the vec to r 1c l c , c l e a r a l lnd=20; % number o f e lementsv=f i x (1000∗ rand (1 , nd ) ) / 1 0 0 ; % genera t ing numbers with two decimal p l a c e svv=v ; % a work vec to rf o r i =1:nd % the s t a r t o f the c y c l e

[ yy i i ]=max( vv ) ; % the l a r g e s t numbery ( i )=yy ; % sav ing o f the numbervv ( i i )=− i n f ; % keeping o f a number to next s t e p e s

endf p r i n t f ( ’ The order o f e lements i s f o l l o w i n g :\n ’ )f p r i n t f ( ’%g\n ’ , y )

% orde r ing o f e lements o f the vec to r 2c l c , c l e a r a l lnd=20; % number o f e lementsv=f i x (1000∗ rand (1 , nd ) ) / 1 0 0 ; % genera t ing numbers with two decimal p l a c e sy=v ; % a work vec to rt e s t =1; % the s t a r t o f the c y c l ewhi l e t e s t

t e s t =0; % i f i t i s not changed , the c y c l e w i l l be f i n i s h e df o r i =2:nd

i f y ( i−1)<y ( i ) ; % the prev ious one i s sma l l e r then the cur rent onez=y ( i −1); % swi tch ing : we remember the prev ious oney ( i−1)=y ( i ) ; % the cur rent one to the prev ious one

21

Page 22: Introduction to Matlab...2 Introduction to programming in the Matlab language 2.1 Introductory notes 1.All variables are matrices. A scalar is a matrix of the type: a(1,1). A vector

y ( i )=z ; % the remembered one to the cur rent onet e s t =1; % i t was a change − do not f i n i s h

endend

endf p r i n t f ( ’ The order o f e lements i s f o l l o w i n g :\n ’ )f p r i n t f ( ’%g\n ’ , y )

%% THE OPTIMIZATION

% Find an extreme o f a s p e c i f i e d func t i on with the help o f the g rad i en t methodc l c , c l e a r a l lf=@(x , y ) . 0 2∗ ( x−1)ˆ2+.1∗(y−2)ˆ2; % a d e f i n i t i o n o f an anonymous func t i on

h=.01; % the step o f s ea r ch ing o f an extremeeps=1e−6; % the smal l number ( a p e r m i s s i b l e e r r o r o f the s ea r ch ing )a l =.1 ; % the weight o f a g rad i en tx=0; y=0; % the s t a r t i n g po int f o r s ea r ch ingj =0; % the counter o f the s tep ( the i n i t i a l i z a t i o n )t e s t =1; % the ente r to the c y c l ewhi l e t e s t

j=j +1; % the updating o f the counterdfx=( f ( x+h , y)− f (x , y ) )/ h ; % the g rad i en t xdfy=( f (x , y+h)− f (x , y ) )/ h ; % the g rad i en t yxn=x−a l ∗dfx ; % the step o f s ea r ch ing ( f o r x )yn=y−a l ∗dfy ; % the step o f s ea r ch ing ( f o r y )d=s q r t ( ( xn−x)ˆ2+(yn−y ) ˆ 2 ) ; % the l ength o f the updated step by sea r ch ingi f d<eps , t e s t =0;end % when the l ength o f the s tep < eps , the end o f the s ea r ch ingx=xn ; y=yn ; % the new one −> the o ld onei f j>1e6 , % the s ea r ch ing does not converge

d i sp ( ’ The permitted number o f i t e r a t i o n s i s exhausted ’ )break

endend% r e s u l t si f t e s t==0

tx=’was ’ ;e l s e

tx=’was not ’ ;endf p r i n t f ( [ ’ The search s o l u t i o n ’ , tx , ’ found − number o f s t ep s %d .\n ’ ] , j )f p r i n t f ( ’ The s o l u t i o n i s [ x , y ] = [%g %g ] . \ n ’ , x , y )

22