BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.

Slides:



Advertisements
Similar presentations
Introduction to Programming using Matlab Session 2 P DuffourJan 2008.
Advertisements

Lecture 14 User-defined functions Function: concept, syntax, and examples © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Lecture 5.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
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.
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Programming with MATLAB
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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.
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Programmer Defined Functions Matthew Verleger. Windows It’s estimated that Window’s XP contains 45 million lines of code (and it’s over 10 years old).
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.
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
C++ for Engineers and Scientists Third Edition
1 Functions Advantages Name, parameters, return info Flow of the data when running functions Menus Functions Applying Functions to Real Projects.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
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”
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.
Getting Started with MATLAB 1. Fundamentals of MATLAB 2. Different Windows of MATLAB 1.
CMPS 1371 Introduction to Computing for Engineers MatLab.
Learners Support Publications Classes and Objects.
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)
COMP 116: Introduction to Scientific Programming Lecture 11: Functions.
Scientific Computing Introduction to Matlab Programming.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Getting Started with MATLAB (part2) 1. Basic Data manipulation 2. Basic Data Understanding 1. The Binary System 2. The ASCII Table 3. Creating Good Variables.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
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.
Digital Image Processing Introduction to M-function Programming.
Introduction to Matlab
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Finding zeros (also called roots) of a function Overview: Define the problem Methods of solution Graphical Newton’s Bisection Secant.
Chapter 9: Value-Returning Functions
User-Written Functions
Scripts & Functions Scripts and functions are contained in .m-files
User-Defined Functions
User Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
MATLAB Programs Chapter 6 Attaway MATLAB 4E.
Functions In Matlab.
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Programming with Matlab
Presentation transcript:

BRIAN D. HAHN AND DANIEL T. VALENTINE THIRD EDITION Essential MATLAB® for Engineers and Scientists

Function M-files The objective of this chapter is to enable you to: - Represent your own functions with inline objects and function M-files. We have already seen that MATLAB has a number of built-in (compiled) functions, e.g. sin, sqrt, sum. You can verify that they are built-in by attempting to type them. Try type sin for example. MATLAB enables you to create your own function M- files.

Cont. A function M-file is similar to a script file in that it also has a.m extension. a function M-file differs from a script file in that a function M-fil communicates with the MATLAB workspace only through specially designated input and output arguments. Functions are indispensable when it comes to breaking a problem down into manageable logical pieces.

10.1 Some examples Inline objects: harmonic oscillators If two coupled harmonic oscillators, e.g. two masses connected with a spring on a very smooth table, are considered as a single system, the output of the system as a function of time t could be given by something like: - h(t) = cos(8t) + cos(9t) You can represent h (t ) at the command line by creating an inline object as follows: - h = inline( ’cos(8*t) + cos(9*t)’ );

Cont. Now write some MATLAB statements in the Command Window which use your function h to draw the graph: - x = 0 : pi/40 : 6*pi; - plot(x, h(x)), grid The variable t in the inline definition of h is the input argument. It is essentially a ‘dummy’ variable, and serves only to provide input to the function from the outside world. You can use any variable name here; it doesn’t have to be the same as the one used when you invoke (use) the function.

Cont. You can create functions of more than one argument with inline. For example, - f = inline( ’x.ˆ2 + y.ˆ2’, ’x’, ’y’ ); - f(1, 2) ans = 5

Function M-files: Newton’s method again Newton’s method may be used to solve a general equation f(x) = 0 by repeating the assignment x becomes x – - where f’(x ) (i.e. df/dx ) is the first derivative of f (x) Suppose that f (x)=x 3 +x − 3, i.e. we want to solve the equation x 3 +x − 3= 0.We have to be able to differentiate f(x).That’s quite easy here: f’(x)= 3x We could write inline objects for both f (x) and f’(x), but for this example we will use function M-files instead.

Cont. Use the Editor to create and save (in the current MATLAB directory) the function file f.m as follows: - function y = f(x) - y = xˆ3 + x - 3; Then create and save another function file df.m : - function y = df(x) - y = 3*xˆ2 + 1; Now write a separate script file, newtgen.m (in the same directory), which will stop either when the relative error in x is less than 10−8, or after 20 steps,

Cont. - % Newton’s method in general - % exclude zero roots! - steps = 0; % iteration counter - x = input( ’Initial guess: ’ ); % estimate of root - re = 1e-8; % required relative error - myrel = 1; - while myrel > re & (steps < 20) - xold = x; - x = x - f(x)/df(x); - steps = steps + 1;

Cont. - disp( [x f(x)] ) - myrel = abs((x-xold)/x); - end; - if myrel <= re - disp( ’Zero found at’ ) - disp( x ) - else - disp( ’Zero NOT found’ ) - end; Note that there are two conditions that will stop the while loop: convergence, or the completion of 20 steps.

Cont. The variable y in the function files f.m and df.m is the output argument. It is a dummy variable, and defines how output will be sent back to the outside world. By the way, you realize of course that you can use your own functions from the command line, don’t you? For example, - f(2) - should return 7 with f.m defined as above.

10.2 Basic rules Try the following more general example, which returns the mean (avg ) and standard deviation (stdev) of the values in the vector x. Although there are two MATLAB functions to do this (mean and std ), it is useful to have them combined into one. Write a function file stats.m : - function [avg, stdev] = stats( x ) - avg = mean(x); % function body - stdev = std(x);

Cont. A function M-file name.m has the following general form: - function [ outarg1, outarg2, … ] = name ( inarg1, inarg2, … ) - % comments to be displayed with help... - outarg1 =... ; - outarg2 =... ;... function keyword: The function file must start with the keyword function (in the function definition line).

Cont. Input and output arguments: The input and output arguments (inarg1, outarg1, etc.) are ‘dummy’ variables, and serve only to define the function’s means of communication with the workspace. You can think of the actual input arguments being copied into the dummy input arguments when the function is called. So when stats(r) is called in the above example, the actual input argument r is copied into the input argument x in the function file.

Cont. Multiple output arguments: If there is more than one output argument, the output arguments must be separated by commas and enclosed in square brackets in the function definition line. When a function is called with more than one output argument, the actual output arguments may be separated by commas or spaces. Naming convention for functions: Function names must follow the MATLAB rules for variable names. If the filename and the function definition line name are different, the internal name is ignored.

Cont. When you type help function_name,MATLAB displays the comment lines that appear between the function definition line and the first non-comment line. Local variables: scope - Any variables defined inside a function are inaccessible outside the function. Such variables are called local variables.

Cont. Global variables: Variables which are defined in the base workspace are not normally accessible inside functions, i.e. their scope is restricted to the workspace itself, unless they have been declared global, e.g. - global PLINK PLONK If several functions, and possibly the base workspace, all declare particular variables as global, then they all share single copies of those variables. MATLAB recommends that global variables be typed in capital letters, to remind you that they are global.

Cont. The function isglobal(A) returns 1 if A is global, and 0 otherwise. The command who global gives a list of global variables. Use clear global to make all variables non-global, or clear x to make x non-global. Persistent variables: A variable in a function may be declared persistent. Local variables normally cease to exist when a function returns. Persistent variables, however, remain in existence between function calls.

Cont. In the following example, the persistent variable count is used to count how many times the function test is called: - function test - persistent count - if isempty(count) - count = 1 - else - count = count end Persistent variables remain in memory until the M-file is cleared or changed. e.g. clear test

Cont. The function mlock inside an M-file prevents the M-file from being cleared. A locked M-file is unlocked with munlock. The function mislocked indicates whether an M-file can be cleared or not. Functions that do not return values: You might want to write a function that doesn’t return values. In that case you simply omit the output argument(s) and the equal sign in the function definition line. - function cube(x) - z = x * x * x; - disp (z)

Cont. Vector arguments: - the following function generates a vector of n random rolls of a die: - function d = dice( n ) - d = floor( 6 * rand(1, n) + 1 ); When an output argument is a vector, it is initialized each time the function is called, any previous elements being cleared. Its size at any moment is therefore determined by the most recent call of the function.

Cont. If a function changes the value of any of its input arguments, the change is not reflected in the actual input argument on return to the workspace (unless the function is called with the same input and output argument—see below). A function may be called with the same actual input and output argument. For example, the following function prune.m removes all the zero elements from its input argument: - function y = prune(x) - y = x(x ˜= 0); You can use it to remove all the zero elements of the vector x as follows: - x = prune(x)

Cont. A function may be called with all, some, or none of its input arguments. If called with no arguments, the parentheses must be omitted. You may not use more input arguments than appear in its definition. The same applies to output arguments. If you call a function with no output arguments, the value of the first one in the definition is returned.

Cont. There are times when a function may need to know how many input/ output arguments are used on a particular call. - In that case, the functions nargin and nargout can be used to determine the number of actual input and output arguments. For example, - function y = foo(a, b, c); - disp( nargin ); will display the number of input arguments present on each call of foo.

Subfunctions A function M-file may contain the code for more than one function. The first function in a file is the primary function, and is the one invoked with the M-file name. Additional functions in the file are called subfunctions, and are visible only to the primary function and to other subfunctions. Each subfunction begins with its own function definition line.

P-code files The first time a function is called during a MATLAB session it is parsed (‘compiled’)into pseudocode and stored in memory to obviate the need for it to be parsed again during the current session. The pseudocode remains in memory until you clear it with clear function_name. You can use the pcode function to save the parsed version of an M-file for use in later MATLAB sessions, or by users from whom you want to hide your algorithms. For example, the command - pcode stats Parses stats.m and stores the resulting pseudocode in the file named stats.p.

cont

Cont. function s = SquareRoot(a) if a > 0 tol = ; x = a / 2; while(1) y = (x + a / x) / 2; e = abs((y - x) / y); x = y; if e < tol, break, end end s = x; else s = 0; end