intro matlab 2 - university of...

31
Introduction to Matlab Part 2 Deniz Savas and Mike Griffiths Corporate Information and Computing Services The University of Sheffield 2012 [email protected] [email protected]

Upload: others

Post on 31-May-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Introduction to MatlabPart 2

Deniz Savas and Mike GriffithsCorporate Information and Computing Services

The University of Sheffield2012

[email protected]@sheffield.ac.uk

Page 2: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Part 2: Topics Covered

• Relational Operations

• Flow Control statements• Using the Toolboxes

• Debugging and Profiling Matlab Scripts

Page 3: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 a nd shape whose each element contain only 1 ( to imply TRUE) or 0 (to imply FALSE ) .

Page 4: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 1while 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.

Page 5: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 xormeaning “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)

Page 6: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 7: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 8: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

if statements

if logical_expressionstatement(s)

endor

if logical_expressionstatement(s)

else statement(s)

endor ...

Page 9: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

if statements continued...

if logical_expressionstatement(s)

elseif logical_expressionstatement(s)

else

statement(s)end

Page 10: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 elem ents evaluated to TRUE

Page 11: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 12: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 13: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

for loops continued ...

• EXAMPLES:sum = 0.0for v = 1:5

sum = sum + 1.0/vendbelow example evaluates the loop with v set to 1,3,5, …, 11

for v = 1:2:11statement(s)

end

Page 14: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

for loops examples

w = [ 1 5 2 4.5 6 ]% here a will take values 1 ,5 ,2 so on..

for a = wstatement(s)

endA= 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 = Astatement(s)

end

Page 15: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Practice Session

Perform 5.Exercises on Matlab Programming on the exercises sheet.

Page 16: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

while loops

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

• SYNTAX:

while expression

:

statement(s)

:

end

Page 17: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

while loops continued ..

• Example:

n = 1while prod(1:n) < 1E100

n= n + 1end

• 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 18: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Practice Session

Perform Exercises 5b on the Exercises Sheet

Page 19: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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.

Page 20: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 21: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 22: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 functionalthough 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 causean early exit from it.

Page 23: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

try … catch construct

This is Matlab’s version of error trapping mechanism.Syntax:

try, statement,

catch, statement,

endWhen 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 24: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 ?

Page 25: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Keyboard User Interactions

• Prompting for input and reading it can beachieved 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 26: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

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 27: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Practice Session

Add course/root into the Matlab PathRun plotroot command to investigate its behaviourUse the built-in Matlab Editor to edit plotroot and

comment out the pause statement.Set a break-point within the program and use the

debugger to investigate its progress.Hint: F12 can be used for setting break-points

Page 28: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Matlab ProfilerThis facility was enhanced at version 6.x, which enables us to investigate the

time taken to run a matlab task or a script. The profiling reports help us to improve the efficiency of the code by pin-pointing the parts of the code that takes most of the time.

Type profile on to start profiling,Run the code or scripts you want to time,Type profile viewer to stop profiling and view the profile report file that has

been automatically generated. You must also use profile clear if you wish to clear the previous statistics.Alternatively click on the profiler icon on the toolbar,In the run this code field enter the name of your script file, or keep that field

clear and just click on Start profiling followed by running your task as usual from the Matlab Command Window and when finish click on the stop profiling icon.

Clicking on the profiling summary icon will display a profile summary which can be expanded by clicking on the routine names on the list.

Page 29: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Extending Matlab ’s capabilities Toolboxes & Matlab -Central

Toolboxes are collections of functions for tackling particular classes of problems. They can be free or only commercially available.

They may have to be purchased separately. See: http://www.sheffield.ac.uk/wrgrid/software/matlab

Use the ver command to list the toolboxes that are currently installed and also their version numbers.

Also the path command will give an indication of the installed toolboxes.

By joining the Matlab-Users community you can share your Matlab code with others and download their code.

See: http://www.mathworks.com/matlabcentral/

Page 30: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

Current list of Toolboxeswe have at Sheffield

• SIMULINK

• Control Systems

• Signal Processing

• M-u analysis

• Fuzzy Logic

• Neural Networks

• Optimisation

• Statistics

• Symbolic maths

• Image Processing

• Mapping

• Wavelet

Page 31: intro matlab 2 - University of Sheffielddsavas.staff.shef.ac.uk/teaching/matlab/intro_matlab_2.pdf• break out of the while and for control structures. Note that there are no go to

THE END