Matlab for Engineers Alistair Johnson 5th October 2011 Centre for Doctoral Training in Healthcare...

Preview:

Citation preview

Matlab for Engineers 

Alistair Johnson 

5th October 2011

Centre for Doctoral Training in Healthcare InnovationInstitute of Biomedical EngineeringDepartment of Engineering Science

University of OxfordSupported by the RCUK Digital Economy Programme grant number EP/G036861/1 

Overview

1. Functions vs scripts (AJ) [1.30pm-2.30pm]o First - commenting your codeo Writing a functiono Checking syntax of argumentso Function Handleso Help files

2. Parallel computing (AJ) [2.30pm - 3.15pm] o Simple parallelisationo Dividing across your processorso Recovering from crashes - indexing your jobs to pick up where you left offo Worked examples using an optimization processo how to execute remotely - sending tasks to a cluster

Commenting your code

 

Commenting

• Commenting is vital for not only others to understand your code (i.e. supervisor), but for yourself later

    “Commenting your code is like cleaning your bathroom—you never want to do it, but it really does create a more pleasant experience for

you and your guests.”

• Commenting properly will never lead to this situation - you should comment your code as you write it, not after.

Compare:

Compare:

Commenting new files

TODO:1.... add syntax to the header comment2.... add examples to the header comment3.... describe the inputs4.... describe the outputs5.... copyright and licensing6.... don't forget SI units where needed!7.… set up source code control to auto-comment version:

* SVN revision information:  * @version $Revision: 82 $:  * @author  $Author: smoot $:  * @date    $Date: 2010-07-10 08:36:02 +0200 (Sat, 10 Jul 2010) $

Provided function: newfun.m

(generates the structure of a new function for you!)Try it out now!

Function Basics

Function Types and ScopeFunction Input/Output

Help files

Function Types and Scope

• Primary Function• Subfunction• Nested Function• Overloaded Function• Anonymous Function• Private Function

Primary Function

• Basic function type• Requires first line to be function definition line

Primary Function

Subfunction

• Functions embedded within a primary function• Appear after primary function's body

Nested Function

• Function within another function

• Inherits the workspace of the parent function

• Cannot be used inside program control statements (e.g., if, switch, try...)

• Can nest functions within functions

Nested Function

Nested Function

Overloaded Functions

• When two functions must have different functionalities for different types of inputs

• Each function must go in a class path

• Example:o ~/home/alistair/@double/calc_average.mo ~/home/alistair/@int32/calc_average.m

Overloaded Functions

Anonymous Function

• Defined in-line• fhandle = @(arg1,arg2) expression• Useful for quick function handles to pass to other

functionso @(x) x.^2o y=cellfun(@(x) x.^2, X);

Private Function

• Located in a sub-folder named private• Identical to primary function• Only visible to functions in the parent folder• Sub-folder private should NOT be in the

MATLAB path

• Example:

Private Function

Example Execution:

Function Input/Output

• nargin, nargouto Give the number of input/output argumentso Useful for argument checking

Variable Function Inputvarargin• All inputs combined into a cell array

Variable Function Output

• varargout 

Input parser

• MATLAB has an inputParser class which is useful for parsing input arguments... as you might have guessed.

• photoPrint.m is an example MATLAB function which uses the main features of the input parser

• photoPrint.m is a faux function which prints a photo given the filename, file type, and some dimension/quality variables

Help files

• MATLAB Help is, put simply, amazing

Help files

• Be sure to check the user's guide!

Parallel Computing

Parallel Computing ToolboxLicensing

Graphical Processing UnitsPractical Exercise

Parallel Computing

• Some tasks lend themselves nicely to parallelization

• The trade offo Computation Overhead vs Computation Time

• Note that MATLAB already has parallelization!

Parallel Computing Toolbox (PCT)

• You will likely work with parfor loops as opposed to for loops• Simple to use, but they require proper indexing• Maximum 8 threads• A general parallel script may look like this:

parfor

• Variable assignment command line output and graphical displays (i.e. figures) will not display from workers

• Assume all parfor run independent of each other• parfor rules:

o Don't use clear or evalo Don't load/save data in a parfor loopo Don't use break, return, global, or persistento Use feval for function handles

parfor variables

Try to make sure any large arrays are sliced, as this will reduce overhead, i.e.:• All of its first level indices are identical throughout the loop• Exactly one of the first level indices is the loop variable

parfor indexingExample workaround for ensuring a variable is indexed properly

PCT crashes

• A PCT crash will give you the line, but not the workspace

• This can make standard debugging annoying• Usually best to remove "par" from parfor and debug

normally

Miscellaneous PCT tips

Open:

Close:

onCleanup:

Practice!

parfor - simple, but a good way to get started

spmd - complicated, but useful, allows for communication between cores

task - multiple independent programs, too advanced

Parallelizing Peak Detector

Parallel Profiler

Graphics Processing Unit (GPU)

• GPUs can also be used for parallel processing

• GPUs have much more cores (sometimes 512) but less processing power per core

• IBME machines have:o Two NVIDIA Quadro NVS 295 (8 cores each)o Intel Xeon E5520 (4 cores, 8 threads)

GPU speed-up

GPU speed-up

GPU Technical Requirements

• GPU computing requires:o MATLAB 2010b or highero NVIDIA CUDA 1.3 or higher

• Your IBME machines haveo MATLAB 2009o NVIDIA CUDA 1.1

?Ask your supervisor for an upgrade!

Licensing

• Using MATLAB in the IBME (or on campus/after VPN) uses the network license

Licensing

• MATLAB licenses are released:o After closing MATLABo After a period of idle time elapses

Licensing

• Try to release your licenses!• As of Sept 2011, we are restricted to 20 university wide

 lmstat:

Licensing

• Try to release your licenses!• Here is an example of how this can be accomplished:

Matlab ExecutablesMEXBasics

Simple exampleLIBSVM exampleTroubleshooting

MATLAB Executable (MEX)

• Allow MATLAB to run external libraries as if they were .m functions

• Use if...o There exists Fortran, C, or C++ code you want to use in

MATLABo You'd like to speed up computation

MEX Requirements

• You will need a compiler (3rd party software)•  For Windows 64-bit:

o Microsoft Visual C++ 2010 Expresso Microsoft Windows SDK 7.1

• For Linux 64-bit:o  GNU gcc/g++ 4.3 or higher

• For OS X 64-bit:o  Apple XCode 4.0 (Snow Leopard) or 4.1 (Lion)

Select Compiler

• Make sure your compiler is using the right language (C, C++, or Fortran)

• We'll be using C•  mex -setup

• Check your compiler's info:• cc = mex.getCompilerConfigurations

Easy example

LIBSVM Practical Example

• LIBSVM is a C library for SVM classification/regression• We are going to compile it in MATLAB• They have already created a make.m file, so run it!

P.S... Source code control & backups!!!

• You should use subversion control for your code!• Linux

o Should already be installed• Windows

o You will need to take extra steps to install GCC, but it's worth it

• Check the IBME wiki for detailso  www.ibme.ox.ac.uk/ ....

Recommended