Professional Documents
Culture Documents
MATLAB stands for MATrix LABoratory. It is a software used in Mathematical calculations, Algorithm Design, Data Analysis, Simulation and Modeling, Building Graphical User Interfaces, etc., for a host of Engineering and Non Engineering disciplines. 0.1 PURPOSE FOR THE TUTORIAL This Tutorial is designed to help students quickly acquaint themselves with this powerful tool and start building useful applications for their personal and academic use. For Distinction between Tutorial instructions and MATLAB commandswe will be using different fonts.
MATLAB 'Start' Button: Used to open various Toolboxes A Typical MATLAB Workspace Fig 1
1.1 THE VERY BASIC Fig 1 shows a typical MATLAB workspace and lists out the main areas of the Package. The user needs to remember that at anytime the above Layout can be changed by Clicking on the Desktop button on MATLAB Menu (See Fig 1) MATLAB executes commands entered by the user and interprets them and executes them. The user can enter these commands at the prompt (>>). A general syntax to enter a command is : >>matlab_command<pressEnter> Result Examples: >>help Would print out Help Topics among the Toolboxes installed in MATLAB. >>exit Would end current MATLAB session. You'd need to click the MATLAB icon on desktop again to begin a new session. help being a MATLAB command can be searched by typing >>helphelp This would generally provide description of a MATLAB command, its syntax as well as related information to similar commands. For beginners it would be useful to try out the following MATLAB commands: >>helpwin >>demo >>helpops 1.2 MOVING ON TO THE BASIC The general notion of a Command in MATLAB is What exactly does it mean? Unlike compiled languages where a certain structure is followed to execute a program, MATLAB programs(called 'Scripts') and commands are executed by an Interpreter. The Interpreter executes a command if it understands it and prompts a warning message incase it does not understand what the user has typed. For example: >>hep ???Undefinedfunctionorvariable'hep'.
What then does a command consist? >>1+1 ans= 2 >>ans*ans ans= 4 >>x=1 x= %apercentagesignisusedtoaddcomments
1 >>%NoticethattheCommentwillnotbeprinted >> I hope the student now has an idea of a MATLAB command. By typing x=1, the Intepreter understands it to be a command to create a variable x and assign a value '1' to it. The variables created by the Interpreter are stored in a temporary area called the Workspace (See Fig 1) . All variables created are created as Matrices. Notice that the size of variables x,y and zinFig 1, is a 1x1 array. Try the following commands: >>m=[123] m= 123 >>size(m) ans= 13 >>size(ans) ans= 12 %Printsthesizeofansin'ans' %Printsthesizeofminvariable'ans' %misamatrixofsize1x3
Excercise: 1 (a) If >>w=[123;456] w= 123 456 >>size(w) What should it print? Excercise: 1 (b) Type >>helpops Read about the various operators used and their meanings in MATLAB. >>w.^3 What does the above command print?(see 1(a) for the value of 'w') What would happen if you were to type: >>w^3 ? 1.3 MATRICES The Basic Object or Storage unit in MATLAB is a Matrix. All data is stored in the form of either a unidimensional or a multidimensional matrix. This necessarily means that all rules applicable in Matrix Algebra are also applicable when a user tries to perform operations on matrices in MATLAB. And what exactly is a matrix? Simply defined it is an array. The array could be of numbers or characters. >>[123;231] ans= 123 231 By now it must be clear to the reader that the semicolon ';' is used to define the next row of elements in the array. **an MxNmatrix (where M and N>1) must ALWAYS be entered within square brackets [] >>m=[23;4] %wrongassignmentof2x2matrix! ???Errorusing==>vertcat CATargumentsdimensionsarenotconsistent. %Definesa2x3arrayofnumbers
1.3.1 THE SEMICOLON OPERATOR (;) Unlike languages such as C, C++ or Java, statements not terminated by a semicolon in MATLAB are not considered as compile time errors. The semicolon operator is used in MATLAB for three main purposes: a) Not allowing echos from the MATLAB command interpreter. >>m=45; >>m m= 45 b) As a seperator for MATLAB commands: >>n=90;m=34;y=n*m; >>y y= 3060 c) As a seperator for rows while entering data into a Matrix object >>x=[1234;5678;9101112;13141516] x= 1234 5678 9101112 13141516 %typem=45andseethedifference! %GeneratesanechofromtheInterpreter
Question:What'sthedifferencebetween: >>x*x and >>x.*x 1.3.2 CONCATENATING MATRICES Matrices can be easily concatenated using submatrices such as these: >>m0=[123;456]; >>m1=[7;8]; >>m2=[m0m1] m2= 1237 4568 >>m3=[m2;m2*2] m3= 1237 4568 24614 8101216 >>m4=[m3m3;m3m3] m4= 12371237 45684568 2461424614 81012168101216 12371237 45684568 2461424614 81012168101216 TRYTHIS: >>m5=[m3m3*0.1;m3*0.2m3*0.3]; >>m6=m5' >>m7=[[123]',[456]']] >>m8=m7'*m7 >>inv(m8) >>det(m8)
1.3.3 NAMING VARIABLES Variables are named objects in MATLAB which are assigned some values. There are a few rules as to what can consist of a variable name. The following rules apply: a) Maximum length must not exceed 31 characters. b) Names can consist of alphabets and/or numerals but cannot begin with a numeral. It may consist of any number of '_' but no other special characters. c) MATLAB is case sensitive so 'this' is not the same as 'This' A few examples of correct variable names: >>tHIS_IS_a_pretty_long_variable_name=10; >>m012=89.0987; >>A1Name='AvalidMATLABvariablename' Invalid Names: >>myvalue=15; >>_not_even_this=14; >>1name='notapropername' 1.3.4 THE COLON OPERATOR (:) The colon operator (:) can be used in to generate sequences progressing arithemetically: >>x=1:10 x= 12345678910 >>x=[1:5;6:10;11:15] x= 12345 678910 1112131415 >>y=1:0.1:2 y= Columns1through8 1.00001.10001.20001.30001.4000 1.50001.60001.7000 Columns9through11 %createsa1x10matrix
1.80001.90002.0000 Analyse the following commands: x=10:1 t=0:0.01:1 theta=0:1/pi:2*pi deg=0:5:359 l=linspace(0,10,10)%notsurethentype>>helplinspace 1.4 PLOTTING VECTORS MATLAB provides various tools to view results graphically. A few of them will be introduced here. Let us consider generating a sine wave of frequency 1Hz. The commands entered would be as follows: >>t=0:1/pi:2*pi; >>y=sin(t); The first command creates an array t whose values begin at 0 and end at2*pi, seperated equally by 1/pi. The second command creates an array y whose values consist of the sine of individual values of the vector t. >>plot(t,y)%plotsvectorsintheformplot(x_axis,y_axis) On entering the last command another window will popup with the continuous time plot of the sine wave. In order for the plotcommand to run the size(t) must be equal to size(y). A vector cannot be plotted against another vector if the two are of different sizes. Other forms of plots include: stem(y); bar(y); stairs(y); plot(t,y,'*') plot(t,y,'ro') stem(y,'g*:') helpplot
%formoreinformationonplots
3. Flow Control
The main flow control statements in MATLAB are for,while,ifelseand switch statements. The student would do well to read the help details by typing: >>helpfor >>helpwhile >>helpif >>helpelse >>helpswitch These would definitely prove helpful to the student. All the flow control statements check if a given condition or expression is 'true' or 'false', 'true' meaning that the expression is evaluated as 1 or a non-zero number and 'false' if the expression evaluates to 0. The corresponding commands are executed only if the expression evaluates to true. 3.1 The'ifelse' Statement The 'if-else' statements follow the syntax: if<expression>, <Commands> elseif<expression>, <Commands> else <Commands> end The 'if' statement on its own is complete, i.e., it follows the syntax: if<expression>, <Commands> end For every 'if' statement there need not be an 'else' or an 'elseif' statement, but every 'else' and 'elseif' statements must have a corresponding 'if'statement. x=input('Enteranumber:'); if(x<35), %Followingstatementswillbeexecutedonlyif x=x*x; %x<35 disp(x); end
3.2 The forStatement The for statement has the following syntax: for<variable=expression>, <Commands> end As an example, try this on the command window: >>fori=0:10, disp(i*i); end >>%here'sanotherone >>x=0; >>fori=0:10, x=x+i; end >>disp(x) >>%here'sanother >>t=0:0.001:2*pi; >>fori=1:4, subplot(2,2,i); plot(t,sin(t+pi/i)); end 3.3 The while Statement The 'while' statement is similar to the 'for'statement but has a little variation in syntax: while<expression>, <Commands> end An example could be: >>i=1; >>t=0:0.001:2*pi; >>whilei<5, subplot(2,2,i); plot(t,sin(t+pi/i)); i=i+1; end
4. FUNCTIONS
4.1 inline Functions MATLAB has the inline specifier to create inline functions. Inline functions may be considered as user defined Mnemonics that help to achieve simple tasks. Inline Functions may be defined in the command window as: >>f=inline('sqrt(x.^2+y.^2)','x','y') f= Inlinefunction: f(x,y)=sqrt(x.^2+y.^2) The inline function above will compute the hypotenuse of a right angled triangle. The first parameter is a string which consists of the formula to calculate the output. The second and the third (depending on the formula) are the inputs to the inline function. >>f(3,4) ans= 5 >>hypo=f(9,10); >>hypo hypo= 13.4536 Inline functions give the user to simplify their code when repeating certain instances of their code. The repititions could simply be replaced by an inline function.