An Introduction to Scientific Computing using MatLabcsvision.swan.ac.uk/BDML/matlabIntro.pdf ·...
Transcript of An Introduction to Scientific Computing using MatLabcsvision.swan.ac.uk/BDML/matlabIntro.pdf ·...
An Introduction to Scientific Computing using MatLab
Dr. Xianghua Xie, [email protected], http://csvision.swan.ac.uk
Introduction
} Matlab is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices.
} It’s name is derived from MATrix LABoratory.
} Matlab is is widely used as a platform for developing tools for Machine Learning, Computer Vision, Computational Analysis, Artificial Intelligence …
Many of the following slides are adapted from Ian Brooks (Leeds)
MATLAB User Environment
Workspace/Variable Inspector
Command History
Command Window
Getting help
There are several ways of getting help: Basic help on named commands/functions is echoed to the command window by: >> help command-name A complete help system containing full text of manuals is started by: >> doc
Getting help
System Environment
} Windows } MATLAB installed in e.g. c:\matlab6.5 } Your code…anywhere convenient (e.g. h:\matlab)
} Linux (Environment network) } MATLAB installed in e.g. /apps/matlab } Your code in e.g. /home/username/matlab } Your environment configuration in e.g. ~/.matlab
startup.m
} The script $matlab_root\toolbox\local\matlabrc.m is always run at startup – it reads system environment variables etc, and initialises platform dependent settings. If present it will run a user defined initialisation script: startup.m
} Linux: /home/user/matlab/startup.m } Windows: $matlab_root\toolbox\local\startup.m
} Use startup.m for setting paths, forcing preferred settings, etc.
%------------------------------------- % Matlab startup file for IMB's laptop %------------------------------------- %-- add paths for my m-files -- addpath d:/matlab addpath d:/matlab/bulk2.5 addpath d:/matlab/bulk2.6 addpath d:/matlab/coastal addpath d:/matlab/lidar addpath d:/matlab/ndbc addpath d:/matlab/page addpath d:/matlab/sections addpath d:/matlab/sharem addpath d:/matlab/wavelet addpath d:/matlab/LEM addpath d:/matlab/GPSbook addpath d:/matlab/FAAM addpath d:/matlab/FAAM/winds addpath d:/matlab/faam/bae %-- add netCDF toolbox -- addpath c:/matlab701/bin addpath c:/matlab701/bin/win32 addpath d:/matlab/netcdf addpath d:/matlab/netcdf/ncfiles addpath d:/matlab/netcdf/nctype addpath d:/matlab/netcdf/ncutility
%-- add path for generic data -- addpath d:/matlab/coastlines % coastline data addpath d:/cw96/flight_data/jun02 % raw cw96 addpath d:/cw96/flight_data/jun07 % aircraft data addpath d:/cw96/flight_data/jun11 addpath d:/cw96/flight_data/jun12 addpath d:/cw96/flight_data/jun17 addpath d:/cw96/flight_data/jun19 addpath d:/cw96/flight_data/jun21 addpath d:/cw96/flight_data/jun23 addpath d:/cw96/flight_data/jun26 addpath d:/cw96/flight_data/jun29 addpath d:/cw96/flight_data/jul01 addpath d:/cw96/runs % run definitions for cw96 flights %---------------------------------------------------------------------- %-- set default figure options -- set(0,'DefaultFigurePaperType','a4') % this should be the default in EU anyway set(0,'DefaultFigurePaperUnits','inches') % v6 defaults to cm for EU countries set(0,'DefaultFigureRenderer','painters') % v7 default OpenGL causes problems
Example startup.m file
The WORKSPACE
} MATLAB maintains an active workspace, any variables (data) loaded or defined here are always available.
} Some commands to examine workspace, move around, etc:
>> who Your variables are: x y
who : lists variables in workspace
>> whos Name Size Bytes Class x 3x1 24 double array y 3x2 48 double array Grand total is 9 elements using 72 bytes
whos : lists names and basic properties of variables in the workspace
>> pwd ans = D:\ >> cd cw96\jun02 >> dir . 30m_wtv.mat edson2km.mat jun02_30m_runs.mat .. 960602_sst.mat edson_2km_bulk.mat
pwd, cd, dir, ls : similar to operating system
>> x=[1 2 3] x = 1 2 3 >> x=[1,2,3] x = 1 2 3 >> x=[1 2 3 4]; >> x=[1;2;3;4] x = 1 2 3 4
When defining variables, a space or comma separates elements on a row.
A newline or semicolon forces a new row; these 2 statements are equivalent. NB. you can break definitions across multiple lines.
} 1 & 2D arrays are treated as formal matrices } Matrix algebra works by default:
>> a=[1 2]; >> b=[3 4]; >> a*b ans =
11 >> b*a ans =
3 6 4 8
1x2 row oriented array (vector) (Trailing semicolon suppresses display of output)
2x1 column oriented array
Result of matrix multiplication depends on order of terms (non-cummutative)
>> a=[1 2] A =
1 2 >> b=[3 4]; >> a.*b ans =
3 8 >> c=a+b c =
4 6
Matrix addition & subtraction operate element-by-element anyway. Dimensions of matrix must still match!
No trailing semicolon, immediate display of result
Element-by-element multiplication
>> A = [1:3;4:6;7:9] A = 1 2 3 4 5 6 7 8 9 >> mean(A) ans = 4 5 6 >> sum(A) ans = 12 15 18
Most common functions operate on columns by default
INDEXING ARRAYS
} MATLAB indexes arrays: } 1 to N } [row,column]
[1,1 1,2 . 1,n
2,1 2,2 . 2,n
3,1 3,2 . 3,n . . .
m,1 m,2 . m,n]
n
m
>> A = [1:3;4:6;7:9] A = 1 2 3 4 5 6 7 8 9 >> A(2,3) ans =
6 >> A(1:3,2) ans =
2 5 8
>> A(2,:) ans =
4 5 6
The colon indicates a range, a:b (a to b)
A colon on its own indicates ALL values
THE COLON OPERATOR
} Colon operator occurs in several forms } To indicate a range (as above) } To indicate a range with non-unit increment
>> N = 5:10:35
N =
5 15 25 35
>> P = [1:3; 30:-10:10]
P =
1 2 3
30 20 10
Basic Operators
+, -, *, / : basic numeric operators \ : left division (matrix division) ^ : raise to power ’ : transpose (of matrix) – flip along diagonal Example: Least square optimisation
>> X=[1,1;3,1;5,1;7,1]; >> y=[2,2,4,5]'; >> a=inv(X'*X)*X'*y;
SAVING DATA
} MATLAB uses its own platform independent file format for saving data – files have a .mat extension } The ‘save’ command saves variables from the workspace to a
named file (or matlab.mat if no filename given) } save filename – saves entire workspace to filename.mat } save var1 var2 … filename – saves named variables to
filename.mat
} By default save overwrites an existing file of the same name, the –append switch forces appending data to an existing file (but variables of same name will be overwritten!) } save var1 var2 filename -append
} Data is recovered with the ‘load’ command } load filename – loads entire .mat file } load filename var1 var2 …– loads named variables
} load filename –ascii – loads contents of an ascii flatfile in a variable ‘filename’. The ascii file must contain a rectangular array of numbers so that it loads into a single matrix.
} X=load(‘filename’,’-ascii’) – loads the ascii file into a variable ‘X’
} save var1 filename –ascii – saves a single variable to an ascii flat file (rectangular array of numbers)
} Script & function
Scripts
} It is possible to achieve a lot simply by executing one command at a time on the command line
} It is easier & more efficient to save extended sets of commands as a script – a simple ascii file with a ‘.m’ file extension, containing all the commands you wish to run.
} The script is run by entering its filename (without .m extension)
} In order for MATLAB to see a script it must be: } In the current working directory, or } In a directory on the current path
Functions
} A MATLAB function is very similar to a script, but: } Starts with a function declaration line } May have defined input arguments } May have defined output arguments
function [out1,out2]=function_name(in1)
} Executes in its own workspace: it CANNOT see, or modify variables in the calling workspace – values must be passed as input & output variables
function [x1,x2,x3]=powers1to3(n)
% calculate first three powers of [1:n]
% (a trivial example function)
x1=[1:n];
x2=x1.^2;
x3=x1.^3;
>> [x1,x2,x3]=powers1to3(4) x1 = 1 2 3 4 x2 = 1 4 9 16 x3 = 1 8 27 64
>> [x1,x2]=powers1to3(4) x1 = 1 2 3 4 x2 = 1 4 9 16
If fewer output parameters used than are declared, only those used are returned.
} There are many functions built-in or supplied with MATLAB. } A few very basic functions are built in to the matlab executable } Very many more are supplied as m-files; the code can be
viewed by entering: >> type function_name
} Supplied m-files can be found, grouped by category, in $matlab_root/toolbox/catagory
Function Help
} MATLAB uses the ‘%’ character to start a comment – everything on line after ‘%’ is ignored
} A contiguous block of comment lines following the first comment, is treated as the ‘help’ text for the function. This block is echoed to screen when you enter >> help function_name This is very useful…use it when writing code!
>> help epot MATLAB FUNCTION EPOT Calculates theta_e by Bolton's formula (Monthly Weather Review 1980 vol.108, 1046-1053) usage: epot=epot(ta,dp,pr) outputs epot : equivalent potential temperature (K) inputs ta : air temp (K) dp : dew point (K) pr : static pressure (mb) IM Brooks : july22 1994
e.g. help text from a function to calculate equivalent potential temperature
function epot=epot(ta,dp,pr) % MATLAB FUNCTION EPOT % Calculates theta_e by Bolton's formula (Monthly Weather % Review 1980 vol.108, 1046-1053) % % usage: epot=epot(ta,dp,pr) % % outputs % epot : equivalent potential temperature (K) % inputs ta : air temp (K) % dp : dew point (K) % pr : static pressure (mb) % % IM Brooks : july22 1994 % ensure temperatures are in kelvin ta(ta<100)=ta(ta<100)+273.15; dp(dp<100)=dp(dp<100)+273.15; % where dewpoint>temp, set dewpoint equal to temp dp(dp>ta)=ta(dp>ta); % calculate water vapour pressure and mass mixing ratio mr=mmr(dp,pr); vap=vp(dp); % calculate temperature at the lifing condensation level TL=(2840./(3.5*log(ta) - log(vap) - 4.805))+55; % calculate theta_e epot=ta.*((1000./pr).^(0.2854*(1-0.28E-3*mr))).* ... exp((3.376./TL - 0.00254).*mr.*(1+0.81E-3*mr));
What it does
How it’s called
What input and outputs are (and units!)
Good coding practice, note what and why…you will forget
If, else, elseif
if condition statements; elseif condition statements; else statements; end
Generic form:
if A<0 disp(‘A is negative’) elseif A>0 disp(‘A is positive’) else disp(‘A is neither’) end
example
switch, case
switch statement case value1 statements; case value2 statements; case value2 statements; otherwise statements; end
Generic form:
switch A*B case 0 disp(‘A or B is zero’) case 1 disp(‘A*B equals 1’) case C*D disp(‘A*B equals C*D’) otherwise disp(‘no cases match’) end
example
for & while loops
for n=firstn:dn:lastn statements; end
FOR: Generic form:
for n = 1:10 x(n)=n^2; end
example
N.B. loops are rather inefficient in MATLAB (and IDL), the example above would execute much faster if vectorized as
>> x=[1:10].^2;
If you can vectorize code instead of using a loop, do so.
while condition statements; end
WHILE: Generic form:
n = 1; while n <= 10 x(n)=n^2; n=n+1; end
example
strings
} MATLAB treats strings as arrays of characters } A 2D ‘string’ matrix must have the same number of characters
on each row!
>> name = [‘Ian’,’Brooks’] name =
IanBrooks >> name=[‘Ian';‘Brooks'] ??? Error using ==> vertcat All rows in the bracketed expression must have the same number of columns >> name=[‘Ian ';‘Brooks'] Name =
Ian Brooks
Cell arrays
} Cell arrays are arrays of arbitrary data objects, as a whole they are dimensioned similar to regular arrays/matrices, but each element can hold any valid matlab data object: a single number, a matrix or array, a string, another cell array…
} They are indexed in the same manner as ordinary arrays, but with curly brackets
} Also support Structure Array
>> X{1}=[1 2 3 4]; >> X{2}=‘some random text’ X = [1x4 double] 'some random text'
} Graphical output
Basic Plotting Commands
} figure : creates a new figure window } plot(x) : plots line graph of x vs index
number of array } plot(x,y) : plots line graph of x vs y } plot(x,y,'r--')
: plots x vs y with linetype specified in string : 'r' = red, 'g'=green, etc '-' solid line, '- -' dashed, 'o'
>> plot(glon,glat) >> xlabel('Longitude') >> ylabel('Latitude') >> title('Flight Track : CW96 960607')
Subplots
} subplot(m,n,p) : create a subplot in an array of axes
>> subplot(2,3,1);
>> subplot(2,3,4);
m
n
P=1 P=2 P=3
P=4
>> peaks;
Peaks is an example function, useful for demonstrating 3D data, contouring, etc. Figure above is its default output. P=peaks; - return data matrix for replotting…
>> P = peaks; >> contour(P)
>> contourf(P,[-9:0.5:9]); >> colorbar
>> colormap cool
Object select Add/edit text
Add arrow & line zoom
3D rotate