intro matlab 2 - university of...
TRANSCRIPT
Introduction to MatlabPart 2
Deniz Savas and Mike GriffithsCorporate Information and Computing Services
The University of Sheffield2012
[email protected]@sheffield.ac.uk
Part 2: Topics Covered
• Relational Operations
• Flow Control statements• Using the Toolboxes
• Debugging and Profiling Matlab Scripts
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 ) .
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.
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)
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_expressionstatement(s)
endor
if logical_expressionstatement(s)
else statement(s)
endor ...
if statements continued...
if logical_expressionstatement(s)
elseif logical_expressionstatement(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 elem ents 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.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
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
Practice Session
Perform 5.Exercises on Matlab Programming on the exercises sheet.
while loops
• while loops repeat a group of statements under the control of alogical condition.
• SYNTAX:
while expression
:
statement(s)
:
end
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.
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.')
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 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.
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.
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 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 .
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
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
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.
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/
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
THE END