MATLAB A brief introduction to programming 1) Background and Getting Started Dartmouth College now has a site license http://caligari.dartmouth.edu/downloads/matlab Installs on Mac, Windows, or Linux Running in the BIL (Linux): Command “matlab” launches latest installed version Currently, most machines default to MATLAB 8.3 (R2014a) or 8.0 (R2013b) Launching MATLAB [aic-bil-ibm1] % matlab & (&: don’t wait for it to quit in this shell) The MATLAB Path The “path” is an ordered list of directories used to match commands to files >> path >> addpath xyz >> which abc list the current path add xyz to the path (for this session only) if abc is a command, give file it runs from 2) MATLAB Data & Variables Numbers in MATLAB are “floating point” (not integer) Some image types are int or unsigned int For the most part, floats are fine for anything numeric Other basic data types are char (characters), struct (data structure), and cell (list element) Basic Data Types Most types can be turned into arrays: Numbers: vectors Chars: strings (or character arrays) Structs: struct arrays Cells: cell arrays Arrays elements are accessed with “( )” (cell arrays also use “{ }”) Variables Note that variable names are case sensitive: A ≠ a To see current variables in MATLAB: >> whos Examples Create a vector (number array): >> a = [ 0 1 2 5 ] (brackets) Create a string (char array): >> b = 'my string’ (single quotes) Create a cell array: >> c{1} = a (allows mixing of >> c{2} = b various types) OR: >> c = { [ 0 1 2 5 ], ‘my string’ } 3) Scripts and Functions Scripts are MATLAB commands saved into a file Exactly equivalent to typing in MATLAB All variables remain after execution Functions are packaged scripts that operate in their own environments Input in, output out Only designated output remains Recommendations Use scripts for quicker work Easier to debug, when small Can access all calculated values Use functions for larger projects and reusable code Less likely to cause trouble (multiple definition of variables, interdependencies) “Cleaner” and more easily verified How To… Create a script: Save commands in a file ending with ‘.m’ Note: file must be in the path to execute! Create a function: as above, but start with a “function” line: e.g. or or function myfunc function x = myfunc(y) function [x1, x2] = myfunc(y1, y2, y3) 4) Help Nearly all commands (all built-in, and most others) have documentation The help command: >> help xyz >> help >> lookfor abc help on command “xyz” list of built-in functions by category search help by keyword 5) The Debugger MATLAB’s debugger can suspend a program while it is executing Way to examine function contents before they are cleared Most frequent usage: >> dbstop if error >> dbquit Go to debugger on error Quit debugger More Debugger Commands Other useful debugger commands: >> dbup Examine calling function >> dbdown Reverse a dbup >> dbstop in xyz at 123 Stop in function xyz at line 123 >> dbclear all Undo current dbstops Tip 1: Continuations You can continue a line on the next line by ending it with “…” >> mylongvariable = {‘mylongstring1’, … >> ‘mylongstring2’, ‘etc.’} (this is particularly helpful in scripts and functions) Tip 2: Command Output You can use “;” to suppress printing of a return value >> x = 5 x= 5 >> y = 3; (the second assignment is made quietly) Tip 3: Notes on ‘cd’ The ‘cd’ command is used to change directories in MATLAB and in Linux… but it works slightly differently >> cd /home/fmri % cd /home/fmri (changes to directory in both) >> cd % cd (prints current directory) (changes to home directory) >> cd(‘/home/fmri’) >> cd(myinputdir) (also legal, and useful with string variables) Tip 4: Shell Commands You can use Linux commands in MATLAB using “!” >> ! rm -r mydir >> ! cp /home/fmri/file1 . (Note: the current directory is always MATLAB’s current directory) Tip (Trick?) 5: Bad Names Beware of using variable names that “shadow” functions (sometimes MATLAB will alert you…) >> end = 1 Error: Illegal use of reserved keyword "end". (…but often it won’t) >> spm = 5 >> spm spm = 5 Tip 6: Clearing Variables You can unassign variables with “clear”: >> clear d* (clear variables starting with “d”) Clearing variables may prevent some problems with scripts >> clear all (clear all variables) Tip 7: Saving a Session The ‘diary’ command can save everything printed in the MATLAB window to a file: >> diary myfile.txt >> diary on … >> diary off Programming Fundamentals » Control - if-then, while loops, and for loops » Expressions - operators and syntax » Output – disp If-Then Loop Structure if expr commands elseif expr commands else commands end % note: can use repeatedly While Loop Structure while expr commands end % evaluated each time! For Loop Structure for var = values commands end % often 1:N % note: evaluated for % each value Expression Format » Expressions are built using operators » Common operators: && - logical AND || - logical OR (note: two vertical pipe symbols) == - test of equality (note: = is assignment) >, <, >=, <= - inequalities ~= and ~ - inequality and negation () - parentheses can be used for grouping Example done = 0; while ~done x = myfunc; if x < 0 || x > 10 done = 1; end end The disp Command » The simplest way to print a variable » Note: non-string variables must be converted to strings: disp(num2str(x)) » Can also display other text: disp(‘Finished:’) disp([‘The value of x is ’ num2str(x)]) First Programming Task » Try to create a small but non-trivial program as an exercise » Example: » Ask the user to pick a date in some way » Compare to today’s date and tell the user how many days until that date comes, or how many days ago it passed Notes » Months have different numbers of days… so this seems non-trivial! » MATLAB functions can help: for example, can use date in MATLAB (it returns a string like ‘10-Apr-08’) and datenum » How should we ask the user for a date? » A calendar looks nice, but this is hard—it will introduce days of the week, which we don’t otherwise need » The menu command can present a list of choices (e.g., ask for a year, a month, and then a day) Other Sample Learning Projects » 1. Get historical population data for NH, VT, and some other states from the Wikipedia, save it to a file, and create code to read it into MATLAB. Write a program that gives users menu options to plot population growth graphs and to use an extrapolation to predict what the population might be in a future year. » New commands to learn: fopen, fread, fclose, plot, hold, legend, polyfit Other Sample Learning Projects » 2. Write a simple DICOM browser. The program should be able to search for a given DICOM file pattern and present a list of files to select from. It should allow a user to see particular fields (by calling Linux tools that can read DICOM fields and parsing their output), or print multiple fields in a tabular view. » New commands to learn: system, listdlg, strfind, strcmp, strrep, sprintf Other Sample Learning Projects » 3. Implement Mad Libs (Mad Lab version?). Create a set of one or more template files that have markers like %NOUN% to replace key words. Read a random template into MATLAB, then ask the user to input an appropriate set of parts of speech, and display the result of substituting these words for the markers. » New commands to learn: fopen, fread, fclose, strrep, rand, round, msgbox