+ All Categories
Home > Documents > INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS...

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

Date post: 07-Aug-2021
Category:
Upload: others
View: 6 times
Download: 0 times
Share this document with a friend
47
INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS DEPARTMENT Deniz Savas & Mike Griffiths July 2018
Transcript
Page 1: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

INTRODUCTION TO MATLABPart2 - Programming

UNIVERSITY OF SHEFFIELD

CiCS DEPARTMENT

Deniz Savas & Mike Griffiths

July 2018

Page 2: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

Outline

• MATLAB Scripts

• Relational Operations

• Program Control Statements

• Writing MATLAB Functions and Scripts

Page 3: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 4: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 5: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 6: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 ) = []

Page 7: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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)

Page 8: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 9: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 10: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

if statements

if logical_expression

statement(s)

endor

if logical_expression

statement(s)

else

statement(s)

endor ...

Page 11: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

if statements continued...

if logical_expression

statement(s)

elseif logical_expression

statement(s)

else

statement(s)

end

Page 12: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 13: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 14: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 15: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 16: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 17: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

while loops

• while loops repeat a group of statements under the control of a logical condition.

• SYNTAX:

while expression

:

statement(s)

:

end

Page 18: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 19: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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)

Page 20: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 21: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 22: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 23: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 24: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 )

Page 25: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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;

Page 26: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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().

Page 27: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 28: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 .

Page 29: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 30: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 31: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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)

Page 32: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 33: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 34: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 35: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 36: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 )

Page 37: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 )

Page 38: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 39: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 40: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 41: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 42: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 43: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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.

Page 44: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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” ;

Page 45: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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 .

Page 46: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

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

Page 47: INTRODUCTION TO MATLAB Part2 - Programming UNIVERSITY OF SHEFFIELD CiCS …dsavas.staff.shef.ac.uk/teaching/matlabintro/matlab2... · 2018. 7. 7. · CiCS DEPARTMENT DenizSavas &

END


Recommended