MATLAB Programs Chapter 6 Attaway MATLAB 4E.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
 2005 Pearson Education, Inc. All rights reserved Introduction.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
CS 201 Functions Debzani Deb.
Introduction to C Programming
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Introduction to Python
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
C++ Programming Language Lecture 2 Problem Analysis and Solution Representation By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structured Programming: Debugging and Practice by the end of this class you should be able to: debug a program using echo printing debug a program using.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Modularity using Functions Chapter 4. Modularity In programming blocks of code often can be "called up" and reused whenever necessary, for example code.
The Hashemite University Computer Engineering Department
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Chapter 9: Value-Returning Functions
User-Written Functions
Chapter 6 JavaScript: Introduction to Scripting
Release Numbers MATLAB is updated regularly
Chapter 7: User-Defined Functions II
SQL and SQL*Plus Interaction
Chapter 4 C Program Control Part I
Chapter 3 Assignment and Interactive Input.
Loops BIS1523 – Lecture 10.
Chapter 6: Modular Programming
© 2016 Pearson Education, Ltd. All rights reserved.
Topics Introduction to Repetition Structures
Chapter 2 Assignment and Interactive Input
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Loop Structures.
Chapter 4 MATLAB Programming
Organization of Programming Languages
Basic operations in Matlab
Functions CIS 40 – Introduction to Programming in Python
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Scripts & Functions Scripts and functions are contained in .m-files
Topics Introduction to Repetition Structures
Programmazione I a.a. 2017/2018.
Intro to PHP & Variables
User-Defined Functions
C++ for Engineers and Scientists Second Edition
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
String Manipulation Chapter 7 Attaway MATLAB 4E.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Introduction to MATLAB Programming
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Chapter 6 Control Statements: Part 2
Loop Statements & Vectorizing Code
Programming Logic and Design Fifth Edition, Comprehensive
Introduction to MATLAB Programming
Topics Introduction to Repetition Structures
Loop Statements & Vectorizing Code
MATLAB Programs Chapter 6 Attaway MATLAB 5E.
Introduction to MATLAB Programming
Introduction to C Programming
CPS125.
CHAPTER 6 Testing and Debugging.
Presentation transcript:

MATLAB Programs Chapter 6 Attaway MATLAB 4E

Types of Functions Categories of functions: They are different in: functions that calculate and return one value functions that calculate and return more than one value functions that just accomplish a task, such as printing, without returning any values They are different in: the way they are called what the function header looks like All are stored in code files with the extension .m

Generic Function Definition All function definitions consist of: The function header The reserved word function Output arguments and the assignment operator (only if the function returns value(s) Function name and input arguments A block comment describing the function The body of the function which includes all statements, including putting values in all output arguments, if there are any end

Functions that Return >1 Value General form of a function that returns more than one value; it has multiple output arguments in the header The output arguments are separated by commas functionname.m function [output arguments] = functionname(input arguments) % Comment describing the function Statements here; these must include putting values in all of the output arguments listed in the header end

Calling the function Since the function is returning multiple values through the output arguments, the function call should be in an assignment statement with multiple variables in a vector on the left-hand side (the same as the number of output arguments in the function header) in order to capture all of them Otherwise, some will be lost

Example Function Call For example, if the function header is: function [x,y,z] = fnname(a,b) This indicates that the function is returning 3 things, so a call to the function might be (assuming a and b are numbers): [g,h,t] = fnname(11, 4.3); Or using the same names as the output arguments (it doesn’t matter since the workspace is not shared): [x,y,z] = fnname(11, 4.3); This function call would only get the first value returned: result = fnname(11, 4.3);

A function tworan that returns two random integers, each in the range from 10 to 20 tworan.m function [ranx, rany] = tworan ranx = randi([10,20]); rany = randi([10,20]); end Example Function call: [x, y] = tworan

A function tworanb that receives two integer arguments a and b and returns two random integers, each in the range from a to b tworanb.m function [ranx, rany] = tworanb(a,b) ranx = randi([a,b]); rany = randi([a,b]); end Example Function call: [x, y] = tworanb(5, 50)

Functions that do not return anything A function that does not return anything has no output arguments in the function header, nor does it have the assignment operator The statements in the body would typically display or plot information from the input arguments functionname.m function functionname(input arguments) % Comment describing the function statements here end

Calling a function with no output Since no value is returned, the call to such a function is a statement For example, if this is the function header: function fnname(x,y) A call to the function might look like this: fnname(x,y) This would NOT be a valid call; since the function is not returning anything, there is no value to assign: result = fnname(x,y); % Invalid!

A function prttworan that prints two random integers, each in the range from 10 to 20 prttworan.m function prttworan fprintf(‘One is %d\n’, randi([10,20])) fprintf(‘The other is %d\n’, randi([10,20])) end Example Function call: prttworan

A function prttworanb that receives two integer arguments a and b and prints two random integers, each in the range from a to b prttworanb.m function prttworanb(a,b) fprintf(‘One is %d\n’, randi([a,b])) fprintf(‘The other is %d\n’, randi([a,b])) end Function call: prttworanb(5,50)

Notes on Functions You do not always have to have input arguments to a function. If you do not, you can have (both in the function header and in the function call) empty (), or you can just leave them out The function header and function call have to match up: the name has to be the same the number of input arguments must be the same the number of variables in the left-hand side of the assignment should be the same as the number of output arguments if there are no output arguments, the function call is a statement Functions that return values do not normally print them, also – that is left to the calling function/script

Program Organization In a modular program, every task is implemented in a function In MATLAB, a program generally consists of a script (the “main program”) that calls functions to accomplish the tasks At the very least, most MATLAB programs consist of a script that calls functions to get the input calculate results display the results

Subfunctions When one function calls another, the two functions can be stored in the same code file with the same name as the primary function primary.m primary function header primary function body includes call to subfunction end subfunction header subfunction body The subfunction can only be called by the primary function

Example: Modular outline In a modular program, a script calls functions Given the following script (where x,y,z are 3 things) [x,y,z] = getinputs; result = calcstuff(x,y,z); displayit(x,y,z, result) With just that information, we can write the corresponding function headers (not the definitions, just the headers)

Example function headers function [x,y,z] = getinputs function result = calcstuff(x,y,z) function displayit(x,y,z, result)

Variable Scope The scope of any variable is the workspace in which it is valid. The workspace created in the Command Window is called the base workspace. Scripts also create variables in the base workspace That means that variables created in the Command Window can be used in scripts and vice versa However, that is very poor programming style Variables defined in functions, however, are local to the function – functions use their own workspaces

Persistent Variables Persistent variables are used only within functions For “normal” variables in functions, memory is allocated when the function is invoked and then released when the function stops executing With persistent variables, the memory stays allocated and the value remains in that location The variable has to be declared as persistent Normally, an if statement is used to check to see if it is empty and if so initializes to a value A counter is a good example: counts how many times the function is called clear functions will reset all persistent variables clear fnname will reset persistent variables in fnname

Persistent Count Example persistex.m % This script demonstrates persistent variables % The first function has a variable "count" fprintf('This is what happens with a "normal" variable:\n') func1 % The second fn has a persistent variable "count" fprintf('\nThis is what happens with a persistent variable:\n') func2 func1.m function func1 % This fn increments a variable "count" count = 0; count = count + 1; fprintf('The value of count is %d\n',count) end func2.m function func2 % This fn increments a persistent variable "count" persistent count if isempty(count) count = 0; end count = count + 1; fprintf('The value of count is %d\n',count)

Types of Errors Syntax errors: mistakes in language e.g. missing quote at the end of a string Run-time (or execution-time) errors: errors that are found during execution of a script or function, e.g. referring to an element in a vector that does not exist Logical errors: mistakes in reasoning e.g. using an expression like (0 < x < 10)

Debugging Methods There are several methods that can be used to find errors: Tracing: using the echo statement which will show all statements as executed Using MATLAB’s Editor/Debugger Set breakpoints so values of variables/expressions can be examined at various points dbstop sets a breakpoint dbcont continues execution dbquit quits debug mode

Function Stubs Function stubs can be used to prevent bugs in the first place The procedure is: Put the “main program” script in place with all function calls Create code files for all functions, which consist solely of the correct function header and a “dummy” body that mimics what the function will eventually do (e.g. return one or more values, or just print something) Then, one by one fill in the actual function bodies

Function Stub Example The lump sum S to be paid when interest on a loan is compounded annually is given by S = P(1 + i)n where P is the principal invested, i is the interest rate and n is the number of years. Write a program that will plot the amount S as it increases through the years from 1 to n. The main script will call a function to prompt the user for the number of years (and error-check to make sure that the user enters a positive integer). The script will then call a function that will plot S for years 1 through n. It will use .05 for the interest rate and $10,000 for P. For now we will write just the script and function stubs.

Script and function stubs % Plots the amount of money in an account % after n years at interest rate i with a % principal p invested % Call a function to prompt for n n = promptyear; % Call a function to plot plots(n, .05, 10000) Note that the function stubs are somewhat nonsensical – BUT – they mimic what the functions will eventually do. The promptyear function will eventually return an integer, and the plots function will eventually plot something. Using the values of n, i, and p ensures they were passed correctly. function outn = promptyear outn = 33; end function plots(n, i, p) plot(n, i*p) end

Live Scripts Live scripts are created using the Live Editor Can embed equations, images, formatted text, and hyperlinks Equations are created using LaTex notation Plots are shown in the live script instead of in separate Figure Windows Live scripts are stored in .mlx files Can be converted to PDF or HTML format

Code Cells and Publishing Code in scripts can be broken into sections called code cells You can run one code cell at a time Code cells are created with comments that start with two %% Code in code cells can also be published in HTML format with plots embedded and with formatted equations Do this from the Publish tab in the Editor

Common Pitfalls Not matching up arguments in a function call with the input arguments in a function header. Not having enough variables in an assignment statement to store all of the values returned by a function through the output arguments. Attempting to call a function that does not return a value from an assignment statement, or from an output statement. Forgetting that persistent variables are updated every time the function in which they are declared is called – whether from a script or from the Command Window.

Programming Style Guidelines If arguments are passed to a function in the function call, do not replace these values by using input in the function itself.  Functions that calculate and return value(s) will not normally also print them.  Functions should not normally be longer than one page in length Do not declare variables in the Command Window and then use them in a script, or vice versa. Pass all values to be used in functions to input arguments in the functions.