Scripts & Functions Scripts and functions are contained in .m-files

Slides:



Advertisements
Similar presentations
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Advertisements

Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Why care about debugging? How many of you have written a program that worked perfectly the first time? No one (including me!) writes a program that works.
CS0004: Introduction to Programming Repetition – Do Loops.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Introducing Algorithms, Pseudocode and.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
CSI 101 Elements of Computing Spring 2009 Lecture #5 Designing with Pseudocode Wednesday, February 4th, 2009.
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.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Agenda Control Flow Statements Purpose test statement if / elif / else Statements for loops while vs. until statements case statement break vs. continue.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 4 – Wage Calculator Application: Introducing.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Matlab Programming, part 1 M-files It is generally more convenient to program in Matlab using m-files, ascii text files containing a set of Matlab commands.
1 Session 3: Flow Control & Functions iNET Academy Open Source Web Programming.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to MATLAB Session 3 Simopekka Vänskä, THL Department of Mathematics and Statistics University of Helsinki 2011.
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
JavaScript, Fourth Edition
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.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
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.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapters 13 and 14 in Quigley's "UNIX Shells by Example"
PHP Condtions and Loops Prepared by Dr. Maher Abuhamdeh.
EEE 161 Applied Electromagnetics
Matlab Training Session 4: Control, Flow and Functions
Topics Introduction to Repetition Structures
Computer Programming I
The Selection Structure
JavaScript: Control Statements.
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
Agenda Control Flow Statements Purpose test statement
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
MATLAB: Structures and File I/O
User Defined Functions
Introduction to MATLAB
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Use of Mathematics using Technology (Maltlab)
Selection Statements Chapter 4 Attaway MATLAB 4E.
Functions In Matlab.
Chapter 2.1 Repetition.
Logical Operations In Matlab.
Topics Introduction to File Input and Output
Selection Statements Chapter 4 Attaway MATLAB 5E.
REPETITION Why Repetition?
Presentation transcript:

Scripts & Functions Scripts and functions are contained in .m-files A script contains a list of commands; when called, it runs these commands. It can access variables in the workspace. Any variables the script creates are retained in the workspace. A function begins with the function keyword. The name of the function must be identical to the file name. Both functions and scripts are called by typing the file name. Functions have a separate workspace, and can only “see” variables sent to it in the calling statement or those generated inside the function; conversely, variables generated inside the functions are not accessible from the workspace. The global function can be used to define variables accessible in several workspaces. The variables must be defined with the same name and preceded by the global keyword in each workspace. The number of input arguments is stored in nargin; the number of output arguments is stored in nargout. After making any modifications, the file must be saved.

Function Structure A function has the following structure (scripts have a similar structure, but lack the first line): Function definition line: this is the first line in the function, and defines the function’s name and its input and output parameters. H1 line – this optional line contains a one-line description of the function. It begins with a % sign. Help text – this optional line (or lines) should contain a more detailed description of the function, including the input and output arguments. All lines in this section start with %. Function body – this is the list of commands which form the function. Comments – comments (which are optional) can be placed at any point in the text, to explain it. They are preceded by the % sign. Function help – when the help function is used with a user-defined function, it will return all the lines following the function definition line which begin with a % sign, until it reaches the first line without such a sign.

The Function Definition Line The function definition line is constructed as follows: function outputArguments=<functionName>(input Arguments) Function names must fulfill the same conditions as variable names (therefore, the isvarname function can be used to check if a function name is valid). The input arguments are the data passed to the function when it is called. They must be valid variables. When the function is called, the arguments in the calling statement are placed in the input argument variable in the corresponding position. The argument names must be separated by commas. It is not necessary to assign data to all input arguments; however, if an argument is referred to without having been given a value, an error will occur. Also, an error will occur if too many input arguments are given. Output arguments contain the data returned to the calling routine. If there is more than one output argument, they must be contained in brackets. Output arguments contain the values they had when the function reaches its end. All arguments must have values at that point.

Function Arguments (cont.) The number of input and output arguments the function can be retrieved with the nargin and nargout functions. In the case of nargin, it checks how many arguments were actually supplied; decision functions may be used to determine alternate courses of action depending on how much data was supplied. A variable number of input arguments can be handled with the varargin function. This functions is used by placing varargin in place of the (or some of the) input arguments in the function definition line. A cell array called varargin is formed, holding all the input arguments supplied, which can be accessed by index. Similarly, the varargout function can be used to return a variable number of output arguments. The output argument in the function definition line must contain [varargout]. Before the function ends, all the output data must be placed in a cell array called varargout. Both varargin and varargout can be in mixed argument lists, but they must be the last arguments in the list. For example, you could write function i=example(a,b,varargin) – the first two input arguments would be placed in a and b, and the rest in varargin.

Decision Handling – the If statement A decision making statement is one which executes different options depending on the result of a test The if statement evaluates a logical expression (which can be true or false). If the statement is true, one sequence of commands is executed. The elseif statement allows the use of a second test evaluation if the first if false, and executes a separate command sequence if it is true. The else statement contains a sequence of commands which is executed if neither the condition in the if statement nor any of the conditions of the elseif statements is true The if..elsif..else sequence is closed by an end keyword. The == operator is used to test whether two scalars are identical or not. To test whether two matrices or vectors are identical, the isequal function is used. Other useful functions are isempty (true if the matrix is empty), all (true if all of the matrix elements are nonzero), and any (true if any of the matrix elements are nonzero). If two matrices (or vectors) are compared using ==, >, etc., the result is a matrix of the same size (both the original matrices must be identical in size) with ‘1’s where the statement is true and ‘0’s where it is false. The statement as a whole is considered true only if all the comparisons are true Logical operators such as & (and), | (or), and ~ (not) can also be used

Decision Handling – the Switch statement The switch statement allows several conditions on a variable to be tested (it is similar to using an if..elseif structure). Each possibility is determined by the case statement. The sequence after the otherwise statement executes if no other case was true. The entire statement is closed by an end keyword

Loops A loop is a section of code that repeats a number of times. A for loop repeats for every one of the elements in its index vector. During each iteration, the current element of the vector is loaded to the index variable. A while loop continues executing so long as a condition is true. The sequence is closed by the end keyword Loops can be nested.

Debugging MatLab contains several functions and tools to assist debugging. The F12 key can be used to set (or remove) breakpoints. These are marked by a red dot to the right of the line, and will cause a function to stop execution when it reaches the breakpoint. When the program stops due to a breakpoint, it is in keyboard mode (marked by a K>> prompt). In that state, the function workspace rather than the normal workspace is available, and function variables can be examined or changed. Once keyboard mode is entered, the F10 key can be used to step through the function line-by-line. Each press of the key will advance program execution by one line, and then return to keyboard mode. Keyboard mode can be entered deliberately by placing a keyboard command in the function. Keyboard mode can be exited with the return function or the F5 key. By using the Stop if Error/Warning option (in the Debug menu), the function can be forced to enter keyboard mode rather than stopping when it encounters an error. This allows the programmer to examine the variable values and determine the cause of the error. The try function is also a useful debugging tool. Its structure is a try keyword, followed by a block of code, followed by a catch keyword, followed by another block of code, and followed by end. Normally, only the section of code between the try and catch keywords is executed. However, if an error is encountered there, execution of that code block stops and the function jumps to the code block following the catch keyword