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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to R Brody Sandel. Topics Approaching your analysis Basic structure of R Basic programming Plotting Spatial data.
R for Macroecology Aarhus University, Spring 2011.
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
COMP 116: Introduction to Scientific Programming Lecture 37: Final Review.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
A MATLAB function is a special type of M-file that runs in its own independent workspace. It receives input data through an input argument list, and returns.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Introduction to M ATLAB 3 Scripts, Functions,…real programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Programming Environment S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: Cells and Structures.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/22/2003.
Introduction to MATLAB Northeastern University: College of Computer and Information Science Co-op Preparation University (CPU) 10/29/2003.
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
Extending MATLAB Write your own scripts and/or functions Scripts and functions are plain text files with extension.m (m-files) To execute commands contained.
Introduction to programming in MATLAB MATLAB can be thought of as an super-powerful graphing calculator Remember the TI-83 from calculus? With many more.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
AN ENGINEER’S GUIDE TO MATLAB
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
MATLAB File Management. MATLAB User File Management Matlab provides a group of commands to manage user files. For more information, type help iofun. pwd.
MATLAB Lecture One Monday 4 July Matlab Melvyn Sim Department of Decision Sciences NUS Business School
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
An Introduction to Unix Shell Scripting
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Shell Script Programming. 2 Using UNIX Shell Scripts Unlike high-level language programs, shell scripts do not have to be converted into machine language.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Files: By the end of this class you should be able to: Prepare for EXAM 1. create an ASCII file describe the nature of an ASCII text Use and describe string.
Digital Image Processing Introduction to M-function Programming.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Introduction to MATLAB Section2, statistics course Third year biomedical dept. Dina El Kholy, Ahmed Dalal.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Using and Programming with MATLAB as an Engineering Tool [ Part III ]
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
An Introduction to Programming in Matlab Emily Blumenthal
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
EEE 161 Applied Electromagnetics
Matlab Training Session 4: Control, Flow and Functions
Scripts & Functions Scripts and functions are contained in .m-files
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
MATLAB: Structures and File I/O
Advanced Data Import & Export Jeff Henrikson
Matlab review Matlab is a numerical analysis system
MATLAB Tutorial Dr. David W. Graham.
T. Jumana Abu Shmais – AOU - Riyadh
funCTIONs and Data Import/Export
INTRODUCTION TO MATLAB
Introduction to MATLAB
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Matlab Basics Tutorial
Presentation transcript:

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

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.

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 = x2 = x3 = >> [x1,x2]=powers1to3(4) x1 = x2 = 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

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.

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, ) 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 : july 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, ) % % 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 : july % ensure temperatures are in kelvin ta(ta<100)=ta(ta<100) ; dp(dp<100)=dp(dp<100) ; % 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) ))+55; % calculate theta_e epot=ta.*((1000./pr).^(0.2854*(1-0.28E-3*mr))).*... exp((3.376./TL ).*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

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.

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

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.

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

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

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

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.

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.

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

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

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’

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

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?

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

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

>> X{1} ans = >> 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’

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

>> 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 :03:54' bytes: 0 isdir: 1

>> dlist(3) ans = name: 'demo.2D.mat' date: '29-Mar :23:40' bytes: 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!