560 likes | 1.14k Views
INTRODUCTION TO MATLAB Part 2 . UNIVERSITY OF SHEFFIELD CiCS DEPARTMENT Deniz Savas & Mike Griffiths MAY.2011. Outline of Part 2. Writing matlab functions and scripts Relational Operations Flow Control statements Basic matlab graphics. Matlab Scripts and Functions.
E N D
INTRODUCTION TO MATLABPart 2 • UNIVERSITY OF SHEFFIELD • CiCS DEPARTMENT • Deniz Savas & Mike Griffiths • MAY.2011
Outline of Part 2 • Writing matlab functions and scripts • Relational Operations • Flow Control statements • Basic matlab graphics
Matlab Scripts and Functions • A sequence of matlab commands can be put into a file which can later be executed by invoking its name. The files which have .m extensions are recognised by Matlab as Matlab Script or Matlab Function files. • If an m file contains the keyword function at the beginning of its first line it is treated as a Matlab function file. • Functions make up the core of Matlab. Most of the Matlab commands “apart from a few built-in ones” are in fact matlab functions.
Accessing the Matlab Functions and Scripts • Most Matlab commands are in fact functions (provided in .m files of the same name) residing in one of the Matlab path directories. See path command. • Matlab searches for scripts and files in the current directory first and then in the Matlab path going from left to right. If more than one function/script exists with the same name, the first one to be found is used. “name-clash” • To avoid inadvertent name-clash problems use the which command to check if a function/script exists with a name before using that name as the name of your own function/script or to find out that the function you are using is really the one you intended to use! • Example : which mysolver • lookfor and what commands can also help locate Matlab functions. • Having located a function use the type command to list its contents.
Differences between scripts and functions • Matlab functions do not use or overwrite any of the variables in the workspace as they work on their own private workspace. • Any variable created within a function is not available when exited from that function. ( Exception to this rule are the Global and Persistent variables)
The function-definition line • General Format: function return_vars = name ( input_args ) Matlab functions can return no value or many values, each of the values being scalars or general matrices. If a function returns no value the format is; function name ( input_args) If the function returns multiple values the format is; function [a,b,c ] = name ( input_args ) If the function name and the filename ‘where the function resides are not the same the filename overrides the function name.
The H1 ( heading line) of function files • Following the function definition line, the next line, if it is a comment is called the H1 line and is treated specially. • Matlab assumes it to be built-in help on the usage of that function. • Comment lines immediately following the H1 comment line are also treated to be part of this built-in help ( until a blank line or an executable statement is encountered) • help function-name command prints out these comment lines, but the lookfor command works only on the first (H1) comment line.
About Functions • Function files can be used to extend Matlab’s features. As a matter of fact most of the Matlab commands and many of the toolboxes are essentially collections of function files. • When Matlab encounters a token ‘i.e a name’ in the command line it performs the following checks until it resolves the action to take; • Check if it is a variable • Check if it is a sub-function • Check if it is a private function • Check to see if it is a p-code or .m file in the Matlab’s search path • When a function is called it gets parsed into Pseudo-Code and stored into Matlab’s memory to save parsing it the next time. • Pre-parsed versions of the functions can be saved as Pseudo-Code (.p) files by using the pcode command. Example : pcode myfunc
Variables in Functions • Function returns values (or alters values) only via their return values or via the global statement. • Functions can not alter the value of its input arguments. For efficiency reasons, where possible, arguments are passed via the address and not via value of the parameters. • Variables created within the function are local to the function alone and not part of the Matlab workspace ( they reside in their own function-workspace) • Such local variables cease to exist once the function is exited, unless they have been declared in a global statement or are declared as persistent. • Global variables: Globalstatement can be used in a function .m file to make variables from the base workspace available. This is equivalent to /common/ features of Fortran and persistent features of C. • Global statement can be used in multiple functions as well as in top level ( to make it available to the workspace )
An example function file. • function xm = mean(x) • % MEAN : Calculate the mean value. • % For vectors: returns mean-value. • % For matrices: returns the mean value of • % each column. • [ m , n ] = size ( x ); • if m = = 1 • m = n ; • end • xm = sum(x)/m;
Function arguments • Functions can have variable numbers of input and output arguments. As well as each argument being a multi-dimensional array. • Size of the input argument arrays can be found by the use of the sizefunction. • The actual numbers of input arguments when the function was called can be found by using the narginfunction • Similarly the actual number of output arguments expected at the time of the call can be deduced by using the nargoutfunction.
Practice Session 4 • Using Matlab Scripts and Functions • Perform exercise 4 on the exercises sheet
Subfunctions • A function m-file can contain many functions. The first one to appear is the primary function (which should have the same name as the m-filename ). The subsequent functions are called the subfunctions and are only visible to the primary function and the other sub-functions in the same m-file.
subfunctions: Example • function [avg,med] = newstats(u) % Primary function • % NEWSTATS Find mean and median with internal functions. • n = length(u); • avg = mean(u,n); • med = median(u,n); • function a = mean(v,n) % Subfunction • % Calculate average. • a = sum(v)/n; • function m = median(v,n) % Subfunction • % Calculate median. • w = sort(v); • if rem(n,2) == 1 • m = w((n+1)/2); • else • m = (w(n/2)+w(n/2+1))/2; • end
Private functions • Private functions are functions that reside in subdirectories with the special name private. They are visible only to the functions in the parent directory. • This feature can be used to over-ride the global functions with your own versions only for certain tasks. This is because Matlab looks into private directory first (if exists) for any function references.
Relational & Logical Operations RELATIONAL OPERATIONS • Comparing scalars, vectors or matrices. < less than <= less than or equal to > greater than >= greater than or equal to = = equal to ~ = not equal to Result is a scalar, vector or matrix of of same size and shape whose each element contain only 1 ( to imply TRUE) or 0 (to imply FALSE ) .
RELATIONAL OPERATIONSCONTINUED • Example 1: A = magic(6) ; A is 6x6 matrix of magic numbers. P = ( rem( A,3) = = 0 ) ; Elements of P divisible by 3 are set to 1 while others will be 0. • Example 2: Find all elements of an array which are greater than 0.7 and set them to 0.5. A = rand(12,1) ;---> a vector of random no.s p = a >= 0.7 ;----> p will be 1’s and 0’s . b = A(find(p>0))=0.5;----> only the elements of A which are >=0.7 will be set to 0.5.
Logical Operations • These are : & (meaning AND) | (meaning OR) ~ (meaning NOT) • Operands are treated as if they contain logical variables by assuming that 0=FALSE NON-ZERO=TRUE • Example : a = [ 0 1 2 0 ] ; b = [ 0 -1 0 8 ] ; • c=a&b will result in c = [ 0 1 0 0 ] • d=a|b will result in d= [ 0 1 1 1 ] • e=~a will result in e= [ 1 0 0 1 ] • There is one other function to complement these operations which is xor meaning “Exclusive-OR”. Therefore; • f = xor( a , b ) will return f= [ 0 0 1 1 ] • ( Note: any non-zero is treated as 1 when logical operation is applied)
Exercises involving Logical Operations & Find function • Type in the following lines to investigate logical operations and also use of the find function when accessing arrays via an indices vector. • A = magic(4) • A>7 • ind = find (A>7) • A(ind) • A(ind)= 0
Summary of Program Control Statements • Conditional control: • if , else , elseif statements • switch statement • Loop control : • for loops • while loops • break statement • continue statement • Error Control: try … catch … end • returnstatement
if statements • if logical_expression • statement(s) • end • or • if logical_expression • statement(s) • else • statement(s) • end • or ...
if statements continued... • if logical_expression • statement(s) • elseif logical_expression • statement(s) • else • statement(s) • end
if statement examples • if a < 0.0 • disp( 'Negative numbers not allowed '); • disp(' setting the value to 0.0 ' ); • a = 0.0 ; • elseif a > 100.0 • disp(' Number too large' ) ; • disp(' setting the value to 100.0 ' ); • a = 100; • end • NOTES: In the above example if ‘a’ was an array or matrix then the condition will be satisfied if and only if all elements evaluated to TRUE
Conditional Control • Logical operations can be freely used in conditional statements. • Example: • if (attendance >= 0.90) & (grade_average >= 50) • passed = 1; • else • failed = 1; • end; • To check the existence of a variable use function exist. • if ~exist( ‘scalevar’ ) • scalevar = 3 • end
for loops • this is the looping control (similar to repeat, do or for constructs in other programming languages): SYNTAX: for v = expression statement(s) end where expression is an array or matrix. If it is an array expression then each element is assigned one by one to v and loop repeated. If matrix expression then each column is assigned to v and the loop repeated. • for loops can be nested within each other
for loops continued ... • EXAMPLES: sum = 0.0 for v = 1:5 sum = sum + 1.0/v end below example evaluates the loop with v set to 1,3,5, …, 11 for v = 1:2:11 statement(s) end
for loops examples • w = [ 1 5 2 4.5 6 ] • % here a will take values 1 ,5 ,2 so on.. • for a = w • statement(s) • end • A= rand( 4,10) • % A is 4 rows and 10 columns. • % Below the for loop will be executed 10 times ( once for each column) and during each iteration v will be a column vector of length 4 rows. • for v = A • statement(s) • end
Practice Session 5 • Perform 5.Exercises on Matlab Programming • on the exercises sheet.
while loops • while loops repeat a group of statements under the control of a logical condition. • SYNTAX: while expression : statement(s) : end
while loops continued .. • Example: n = 1 while prod(1:n) < 1E100 n= n + 1 end • The expression controlling the while loop can be an array or even a matrix expression in which case the while loop is repeated until all the elements of the array or matrix becomes zero.
Practice Session Perform Exercises 5b on the Exercises Sheet
break statement • break out of the while and for control structures. Note that there are no go to or jump statements in Matlab ( goto_less programming ) continue statement This statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop.
break statement example • This loop will repeat until a suitable value of b is entered. • a=5; c=3; • while 1 • b = input ( ‘ Enter a value for b: ‘ ); • if b*b < 4*a*c • disp (‘ There are no real roots ‘); • break • end • end
switch statement Execute only one block from a selection of blocks of code according to the value of a controlling expression. Example: method = 'Bilinear'; % note: lower converts string to lower-case. switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end Note: only the first matching case executes, ‘i.e. control does not drop through’.
return statement • This statement terminates the current sequence of commands and returns the control to the calling function (or keyboard it was called from top level) • There is no need for a return statement at the end of a function although it is perfectly legal to use one. When the program-control reaches the end of a function the control is automatically passed to the calling program. • return may be inserted anywhere in a function or script to cause an early exit from it.
try … catch construct • This is Matlab’s version of error trapping mechanism. • Syntax: • try, • statement, • catch, • statement, • end • When an error occurs within the try-catch block the control transfers to the catch-end block. The function lasterr can than be invoked to see what the error was.
Handling text • Characters & text strings can be entered into Matlab by surrounding them within single quotes. Example: height=‘h’ ; s = ‘my title’ ; • Each character is stored into a single ‘two-byte’ element. • The string is treated as an array. Therefore can be accessed manipulated by using array syntax. For example: s(4:8) will return ‘title’ . • Various ways of conversion to/from character to numeric data is possible; Examples: title=‘my title’ ; double(title) > will display : 109 121 116 105 116 108 101 grav = 9.81; gtitle1 = num2str(grav) > will create string gtitle1=‘9.81’ gtitle2 = sprintf(‘%f ’ , grav) > will create string gtitle2=‘9.8100’ A= [65:75] ; char(A) > will display ABCDEFGHIJK. Now try : A= A+8 ; char(A) What do you see ?
Keyboard User Interactions • Prompting for input and reading it can be achieved by the use of the input function: • Example: n = input ( ‘Enter a number:’ ); will prompt for a number and read it into the variable named n .
Other useful commands to control or monitor execution • echo ------> display each line of command as it executes. echo on or echo off • keyboard------> take keyboard control while executing a Matlab Script. • pause ----- > pause execution until a key presses or a number of seconds passed. pause or pause (n) for n-seconds pause
Graphics with MatlabPart I • Powerful 2D and 3D graphics features are available. • Graphics is built upon a collection of objects whose properties can be altered to change the appearance of graphs. • Graphs may be drawn by using the low-level graphics primitives alone but there are usually higher level functions available for most of the common graphics needs.
Figure Window • Any graphics command will normally use the current figure window ‘if there is one’ or open up a new figure window ‘if there is not one already’ , and will create the plots within that window. • It is always possible to open a new graphics window by using the figure command. Figure windows can later be closed by using the close command or cleared by using the clf command. • When dealing with multiple figure windows, a better control can be applied by using handles. • Example: • h1 = figure; plot(y1); • h2 = figure; plot(y2) ; hold on ; plot(y3) • close (h1) ; clf(h2) ;
2D Plotting Related Functions • plot( x/y) plotting. loglog , semilogx and semilogy are variations of the plot command. • title : adds a title to a plot • xlabel , ylabel: add x and y axis labels • text , gtext: to add arbitrary text on a graph. • grid: adds grid-lines • hold , subplot : To help display multiple plots
x/y line plotting examples • Let x and y be vectors of equal length and A is an n-by-m matrix • plot(x) -----> plots x versus its index. • plot(x,y) -----> plots x versus y • plot(x,y,’string’) ---> as above but also specify the line colour and/or style. Where the string is one or more characters which indicate the colour of the line and optionally the marker type to use the colour indicator is one of c,m,y,r,g,b or w. • the line type character is one of ,o,+,* -,: ,-. or -- . • plot (x,y1,x,y2,x,y3) → plot y1,y2 and y3 using the same x axis and with same scaling. • plotyy(x,y1,x,y2) → plot y1 and y2 against x on same plot but use different scales for each graph.
plot command cont. • When plot is called with a matrix argument each column is plotted as a separate line graph on the same graph with the index being the common x-axis. Example: t = 0:0.1:2*pi; a = [ sin(t) ; cos(t) .*exp(-t) ] ; a = a’; plot(a) Note: dot between cos(t) exp(-t)
Plots used in statistical studies • Bar and area graphs • bar, barh • bar3 , bar3h • Area • errorbar • Pie charts • pie • Histograms • hist , histc
Other useful plotting commands • bar - draws bar charts: bar (rand(1,10) ) • errorbar : plot with error bars • fplot: evaluates a function and plots results with automatic sampling to suit the variation. Example: fplot( 'sin(x).*exp(-x/4)' ,[ 1 10 ] )
Figure : This command creates a new graphics window. Multiple figure windows will happily coexist. Only one of the figures will have the focus for drawing. Hold : Each graph is usually drawn into a clean window, by deleting the current display area. The hold command will over-ride this behaviour and draw the new graph over the existing one. Subplot : This command will divide the current graphics figure into multiple panels and allow you to draw a different graphs in each panel. Example: subplot(2,2,1) ; plot(y1) subplot(2,2,2) ; plot(y2) subplot(2,2,3) ; plot(y3) Plot control commands
Practice Session-6 • Perform exercises 6A on the exercise sheet • After any plotting the figure window will be visible. • It is possible to make changes to this figure by the use of various Matlab commands, which we will learn later. • It is also possible ‘and easier’ to interact directly with the figure via the available figure menus and toolbar icons to change its appearance.
Practice Session 6Perform Exercises 6b from the exercises sheet • Read data in the file field.dat and experiment and observe different plot types by issuing the following commands one at a time ; • load field.dat ;bar(field(:,1) ); barh(field(:,1) ) • bar3(field(:,1));bar3(field(:,1:2) • bar3(field(:,1:2),’group’ ) • area(field(:,3) ; • area(field(:,2:3) % note that area curves are accumulative. • pie(field(:,1) ) ; pie( field(1,:) ) % note values are normalised • pie( field(1,:)./11.0 ) % note that if sum of values less than 1.0 • % no normalization takes place • yy = rand(1000,1); hist(yy ) ; hist(yy, 20 ) • % note that the second parameter specifies number of buckets, default % being 10.