Matlab for Engineers Alistair Johnson 31st May 2012 Centre for Doctoral Training in Healthcare Innovation Institute of Biomedical Engineering Department of Engineering Science University of Oxford Supported by the RCUK Digital Economy Programme grant number EP/G036861/1
Overview 1. 2. 3. 4. 5. 6. Commenting your code Functions overview Function types Function Input/Output Input parsing Memory efficiency Statistics Available stats in MATLAB Useful GUIs Plotting Help
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. Of course - 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:... add syntax to the header comment... add examples to the header comment... describe the inputs... describe the outputs... copyright and licensing... don't forget SI units where needed! Provided function: newfun.m Try it out now!
Function Basics Function Types and Scope Function Input/Output Help files
Function Types and Scope Primary Function Subfunction Nested Function Overloaded Function Private Function Anonymous Function
Function Types and Scope Primary Function Subfunction Nested Function Overloaded Function Private Function Anonymous Function
Primary Function Basic function type Requires first line to be function definition line
Primary Function
Why use a Primary Function? Functions are useful to: Easily re-run code with different inputs Keep code modular Keep code neat!
Subfunction Functions embedded within a primary function Appear after primary function's body
Why a subfunction? Useful for functions which parse input arguments Initializing values (say a vector of coefficients) Repeated calculations used only in the above function
Nested Function Function within another function Inherits the workspace of the parent function Cannot be written inside program control statements (e. g., if, switch, try...) Can nest functions within functions
Nested Function
Why a 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: ~/home/alistair/@double/calc_average.m ~/home/alistair/@int32/calc_average.m
Overloaded Functions
Why an Overloaded Function? Want a function to behave differently if given, e.g., a char or cell input Only really needed if you plan on releasing a robust toolbox of some sort..
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:
Why a Private Function? Prevents MATLAB functions from calling the function you wrote (e.g., you wrote a function called 'predict') Desirable to have non-standard behaviour for some of your functions
Anonymous Function Defined in-line fhandle = @(arg1,arg2) expression Useful for quick function handles to pass to other functions fcn = @(x) x.^2; y=cellfun(@(x) x.^2, X);
Why use an Anonymous Function? When you want to write a quick function ex7_anonymous When you are using cellfun, arrayfun, etc We will go over this later
Function Basics Function Types and Scope Function Input/Output
Function Input/Output nargin, nargout Give the number of input/output arguments Useful for argument checking
Variable Function Input varargin 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. inpparserexample.m is an example MATLAB function which uses the main features of the input parser
Input parser inpparserexample.m inputs are: required optional parameter-value pairs
Saving memory Though your 8GB of memory should handle most things fine - best practice is to not be wasteful
Saving memory 2D grayscale 2D colour 2D time 3D For those doing medical imaging - memory can become a real concern! 8 bytes x 256 x 256 = 0.5 MB 8 bytes x 256 x 256 x 3 = 1.5 MB 8 bytes x 256 x 256 x 3 x 60 = 90 MB 8 bytes x 256 x 256 x 3 x 60 x 80 = 7200 MB
Saving memory Take advantage of copy-on-write behaviour Say you called a function: output = f(x) If you modify x in any way MATLAB copies the array If you do not modify x MATLAB uses the original x
Saving memory Take advantage of in-place operations If... You have a function which modifies a large data array You do not care about the input afterward Then... You should call the function as such: x = f(x) MATLAB will not produce unneeded copies
Saving memory If... Then... You modify parts of an input, but not all of it You should make the input a structure, and only modify some fields Example: ex7_2_savingmemory
Saving memory If you have large data arrays Avoid using large cell arrays with small individual elements each cell has ~80 bytes overhead Preallocate biggest arrays first Consider using nested functions to save passing data to a function that modifies it MATLAB uses a heap - don't worry about the details, just do this Be careful leaving your MATLAB running for too long (~days), Windows will fragment the memory
Statistics Almost all of you will need to use rudimentary statistics eventually e.g. t-test, ks-test,... MATLAB is here to make life easy!
Statistics Which to choose? Is my data normally distributed? [h,p] = jbtest(data)
Type of Data Goal Measurement (from Gaussian Population) Rank, Score, or Measurement (from Non- Gaussian Population) Binomial (Two Possible Outcomes) Describe one group Mean, SD mu = mean(data) sigma = std(data) Median, interquartile range med = median(data) quant = iqr(data) Proportion prop = mean(data) Compare one group to a hypothetical value One-sample t test Wilcoxon test p = signrank(data,val) Chi-square or Binomial test ** [h,p]=vartest(data,var) Compare two unpaired groups e.g., diabetics vs non-diabetics Unpaired t test Mann-Whitney test p = ranksum(data1,data2) Fisher's test [h,p]=vartest2(data1, DATA2) Compare two paired groups e.g., diabetics before and after treatment Paired t test [h,p] = ttest(data1,data2) Wilcoxon test p = signrank(data1,data2) McNemar's test File Exchange Compare three or more unmatched groups One-way ANOVA p = anova1(data) Kruskal-Wallis test p = kruskalwallis(data1) Chi-square test File Exchange Compare three or more matched groups Repeated measures ANOVA p = anovan(data,groups) Friedman test p = friedman(data,reps) Cochrane Q** File Exchange Quantify association between two variables Pearson correlation c = corr(data1,data2,... 'type','pearson') Spearman correlation c = corr(data1,data2,... 'type','spearman') Contingency coefficients** File Exchange [h,p] = ttest(data, VAL) [h,p] = ttest2(data1,data2)
More info with help files MATLAB Help is, put simply, amazing
Help files Always be sure to check the user's guide!
Statistics Many available GUIs!
Plotting You will inevitably have to graph something for your project While excel is nice for plots (I'm lying - it really isn't), MATLAB really excels at visualization
The basics Plotting functions you will use: plot scatter bar stem All of them are very similar - let's look at scatter
Scatter
Subplots
Setting axes If you show multiple plots - consistent axes are a must axis([xmin xmax ymin ymax]); ex6_3_axes
Setting axes axis([xmin xmax ymin ymax]);
Axes properties
Axes properties
Linking axes
Tick Labels
Font sizes!