Presentation is loading. Please wait.

Presentation is loading. Please wait.

M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even.

Similar presentations


Presentation on theme: "M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even."— Presentation transcript:

1 M AT L AB Programming: scripts & functions

2 Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even possible to run loops, if…then conditional statements, etc). 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

3 Scripts are executed in the current workspace – they have access to all existing variables. New variables or changes to existing variables made by the script remain in the workspace after script has finished.

4 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

5 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.

6 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

7 For users on the ENV network: –~ibrooks/matlab (env-fs-05\u12\ibrooks\matlab from windows) lots of (>500) m-files related (more or less) to atmospheric science.

8 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!

9 >> 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

10 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

11 Function arguments [out1,out2]=afunction(in1,in2,in3,in4) Have seen that it is not necessary to use ALL of the output arguments when calling the function. It is possible to write functions to handle variable numbers of inputs & outputs – e.g. use of optional inputs, or changing behaviour in response to number of outputs called. You CANNOT use more inputs/outputs than defined in function declaration.

12 nargin – returns number of input arguments used in function call nargout – returns number of output arguments used in function call function [x,y]=afunction(a,b,c) % …help text… if nargin<3 c=1; end …rest of code… Set a default value if an input variable is not supplied

13 Two special input & output arguments – varargin and varargout – can be used for variable-length input and output argument arrays. f unction varargout=afunction(varargin) Can call a function declared like this with any number of input and output arguments…it is up to the programmer to handle them. Use nargin, nargout to determine number of arguments.

14 Program Control Most programming languages have a similar set of program control features: –Loops ‘for’ loops – counter controlled ‘while’ or ‘repeat until’ loops - condition controlled –If-then conditions –switch/case conditions

15 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

16 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 A case is matched when the switch statement equals the case value (may be the result of a statement). Only first matching case is executed, then switch statement exits, remaining cases are not tested.

17 for loops for n=firstn:dn:lastn statements; end 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. for variable=expression statements; end More generally (but rarely used), if expression returns a matrix, then each column in turn is returned to the control variable

18 while while condition statements; end Generic form: n = 1; while n <= 10 x(n)=n^2; n=n+1; end example The statements within the while loop are executed repeatedly while the condition is true. Example does exactly the same as the for loop in previous example (another inefficient loop). If the condition is false when first tested, the statements in the while loop will never be executed.

19 continue, break, return continue – forces current iteration of loop to stop and execution to resume at the start of next iteration. break – forces loop to exit, and execution to resume at first line after loop. return – forces current function to terminate, and control to be passed back to the calling function or keyboard.

20 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

21 Can concatenate strings as: >> firstname = ‘Ian’; >> secondname = ‘Brooks’; >> fullname = [firstname,‘ ’,secondname] fullname = Ian Brooks Strings defined within single quotation marks  quotation mark within a string needs double quoting >> sillyname = 'Ian ''matlab-guru'' Brooks' sillyname = Ian 'matlab-guru' Brooks

22 Evaluating strings The ‘eval’ function takes a string argument and evaluates it as a MATLAB command line – this can be a useful way of building commands to execute without knowing in advance all of the terms to include. >> filename = input(‘enter filename to save to:’,’s’); enter filename to save to:MyData >> eval([‘save ‘,filename]) First line requests input as a string from the user, this is assigned to the variable ‘filename’ – here the string ‘MyData’ has been entered Second line evaluates/executes the string as ‘save MyData’

23 >> leg1=‘time>45225&time<45825’; >> plot(time(eval(leg1)),alt(eval(leg1))); >> ii=eval(leg1); >> plot(time(ii),alt(ii)); Above is an example of the way I use string evaluation with aircraft data. Flight legs are defined as periods with well defined heading, altitude, etc… I create a set of flight leg definition variables leg1, leg2, etc that can be loaded with the aircraft data. These are simply strings that contain an expression that evaluates to a logical index into the timeseries. One such definition is defined above, the two plot statements (of altitude against time) are equivalent, but one evaluates the expression within the plot statement, the other evaluates it separately.

24 Functional forms of basic commands Most of MATLAB’s basic commands for determining workspace/environment information (who, whos, pwd, dir,…) have a functional form that returns information to a variable rather than simply echoing it to screen. >> vars = who vars = ‘alt’ ‘time’ ‘P’ ‘T’ ‘T2’ Note – strings are of different lengths…how?

25 >> vars = who(‘T*’) vars = ‘T’ ‘T2’ Can also pass a regular expression as an input to match a subset of the variables The different length strings are possible because the ‘who’ function does not return a regular array, but a cell array.

26 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 >> X{1}=[1 2 3 4]; >> X{2}=‘some random text’ X = [1x4 double] 'some random text'

27 >> X{1} ans = 1 2 3 4 >> X{1}(2) ans = 2 Index an array element within a cell, by concatenating the indices: Cell arrays are particularly useful for storing arrays of strings, rather than arrays of characters. >> drinks = {‘beer’,’whisky’,’gin’,’wine’,’water’} drinks = ‘beer’ ‘whisky’ ‘gin’ ‘wine’ ‘water’ >> drinks{4} ans = ‘wine’

28 Structure arrays MATLAB supports structured variables with named fields in a similar manner to other programming languages. The fields can contain any data type. Structured arrays are returned by the functional forms of ‘whos’ and ‘dir’. >> dir. demo.profiles.mat movieframes.mat.. demo.timeseries.mat runQmovie.m demo.2D.mat demomovie.m demo.m demowindmovie.m Simple ‘dir’ command echos directory contents to screen...

29 >> dlist=dir dlist = 10x1 struct array with fields: name date bytes isdir Functional form of ‘dir’ returns filenames, timestamp, size, and a logical flag to indicate if the file is a directory >> dlist(1) ans = name: '.' date: '29-Mar-2005 12:03:54' bytes: 0 isdir: 1

30 >> dlist(3) ans = name: 'demo.2D.mat' date: '29-Mar-2005 12:23:40' bytes: 54436504 isdir: 0 >> dlist(4).name ans = demo.m Again, a pattern matching expression can be provided as input to dir to limit the range of files returned. Could use this as a means to load and process a set of files: >> dlist=dir(‘*.mat’); >> for n=1:length(dlist),eval([‘load ‘,dlist(n).name]), run_my_processing(inputs...); clear all, end >> Note loop run from command line!


Download ppt "M AT L AB Programming: scripts & functions. Scripts It is possible to achieve a lot simply by executing one command at a time on the command line (even."

Similar presentations


Ads by Google