INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS...

Post on 07-Aug-2021

8 views 0 download

Transcript of INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS...

INTRODUCTION TO MATLABPart2 - Programming

UNIVERSITY OF SHEFFIELD

CiCS DEPARTMENT

Deniz Savas & Mike Griffiths

July 2018

Outline

• MATLAB Scripts

• Relational Operations

• Program Control Statements

• Writing MATLAB Functions and Scripts

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 whichcommand 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.

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

A( A >= 0.7 )=0.5; ----> only the elements of A which

are >=0.7 will be set to 0.5.

• Example 3: given a vector of numbers b, eliminate all elements of that vector whose values lie outside the range 0.0 to 100.0

b= ( rand(30,1) -0.1) *120

b( b < 0.0 | b > 100.0 ) = []

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 : If 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 value 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

• return statement

if statements

if logical_expression

statement(s)

endor

if logical_expression

statement(s)

else

statement(s)

endor ...

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 assignedone 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

• Loop counter is a scalarw = [ 1 5 2 4.5 6 ]% here a will take values 1 ,5 ,2 so on..

for a = wstatement(s)

end

• Loop counter is a vector A= rand( 4,10)

% A is 4 rows and 10 columns.

% The for loop below 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

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.

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)

Scripts vs Functions

Script Function

Works in Matlab Workspace

( all variables available)

Works in own workspace

(only the variables passed as arguments to functions are available ) ( exception: global )

Any variable created in a script remains available upon exit

Any variable created in a function is destroyed upon exit exception: persistent

As Matlab workspace is shared communication is possible via the values of variables in the workspace.

Only communications is via parameters passed to functions and value(s) returned via the output variables of functions.

Any alteration to values of variables in a script remains in effect even after returning from that script.

Parameters are passes by reference but any alterations made to these parameters in the called function initiates creation of a copy. This ensures that input parameters remain unaltered in the calling function.

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

– it is an anonymous function

– it is a nested function

– it is a sub-function ( local function )

– it is a private function

– 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 output parameters or via the global statement.

• Functions can not alter the value of its input arguments in the calling routine. For efficiency reasons, where possible, input parameters are passed via the address and not via value but care is taken not to alter the value of input parameters in the calling routine

• 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: Global statement 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 ;endxm = sum(x)/m;

Practice Session 1

Writing Matlab Functions

Perform the first exercise in the exercises_programming file to write a function that calculates the value of sin().

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 size function.

• The actual numbers of input arguments when the function was called can be found by using the nargin function

• Similarly the actual number of output arguments expected at the time of the call can be deduced by using the nargout function.

Example uses of nargin nargout

Number of parameters supplied to a function during a call can be discovered using the nargin() function.

Similarly number of arguments expected to be returned during a call can be discovered using the nargout() function.

For example if a function is referenced as:

[ x , y ] = myfun ( a , b , c , d )

Then in myfun nargin should return 4 and nargout should return 2

Referencing the same function as:z = myfun( e , f )

would result is nargin returning 2 and nargout returning 1 .

Exercises 2

In the programming directory you will find a MATLAB function named mystat1.m. Using that function tackle Exercises 2 from the exercises_programming sheet.

Types of Functions

There are a number of types of functions which differ from each other mainly due to the visibility aspect.

Following slides list these function types.

Anonymous Functions

These are functions created during a session on the fly and not saved into a file. They remain in the memory until cleared

Example: cube = @(x) x.^3 ;

a = cube(3)

Local Functions

• A function m-file can contain a list of 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 local functions and are only visible to the primary function and the other local functions in the same m-file.

Local Functions: 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

Nested Functions

A nested function is a function that is completely contained within another function. They can access all the variables of the containing function

Example:function [avg,med] = newstat2(u) % This is the primary function% NEWSTAT2 Finds mean and median of a vector using nested functions.n = length(u);avg = mean; med = median;

function a = mean % Nested Function% Calculate average.

a = sum(u)/n;endfunction m = median % Nested Function

% Calculate median.w = sort(u);if rem(n,2) == 1

m = w((n+1)/2);elsem = (w(n/2)+w(n/2+1))/2;end

end 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.

Function Handles

• The main use of function handles is to provide the ability to apply the same process to different functions.

• Example: Matlab function integral can be invoked as; integral ( function_handle, lower_limit , upper_limit )

For example: integral (@sin , 0.0 , 2.0 )

integral ( @humps , -1.0 , 2.0 )

Example of a function handle

Create a function file myfun.m which contains the following lines and save it.

function y = myfun ( x )

y = 1.0 + x.*2 - sin( x ).*2 ;

end

You can now find the integral of this function easily by using the integral function. For example:

s = integral ( @myfun , 1 , 10 )

Practice Session 3

In the programming directory you will find a function named findrt1.m.

Using that function perform exercises 3 from the exercises_programming sheet.

break statement

Breaks out of the while and for loop 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.')

endNote: 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

• There are two ways of storing text in MATLAB.1. Character arrays2. Character strings

• Character arrays : This is the traditional method of storing text. They 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 arrays 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 ?

• Character strings have recently (2016) been introduced. A character string is stored by entering the string in double quotes.

Example: anote = “The defining equation” ;

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

END