November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB

Slides:



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

Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Program Design. Objectives Students should understand the basic steps in the programming process. Students should understand the need for good design.
Programming in Visual Basic
MATLAB ME1107 Y Yan Reference: MATLAB for Engineers by Holly Moore (Pearson Prentice Hall)
User-defined Functions. CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello!' ); x = 5;
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
Functions MATLAB’s power comes from functions Functions allow projects to be partitioned into manageable, testable, reusable modules.
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
Lecture Notes 1/21/04 Program Design & Intro to Algorithms.
EGR 106 – Week 8 Data Files & Functions Interacting with Data Files Functions – Concept – Examples and applications Textbook chapter ,
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Algorithms. Introduction Before writing a program: –Have a thorough understanding of the problem –Carefully plan an approach for solving it While writing.
MATLAB and Simulinklecture 31 To days Outline  Functions  Strings  Sparse Arrays  Cell Arrays  Structures  Exercises on this days topics.
Lecture Notes 8/30/05 Program Design & Intro to Algorithms.
Chapter 9 Introduction to Procedures Dr. Ali Can Takinacı İstanbul Technical University Faculty of Naval Architecture and Ocean Engineering İstanbul -
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.
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
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 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Lecture 1: Introduction Lecture series based on the text: Essential MATLAB for Engineers and Scientists By Hahn & Valentine
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Numerical Computation Lecture 7: Finding Inverses: Gauss-Jordan United International College.
Recap Graphic Window Edit Window Start Button Matrices in MATLAB Scalar Operations Order of Operations Array Operations Matrix Addition Matrix Multiplication.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (1): Introduction.
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.
MATLAB Trigonometry, Complex Numbers and Array Operations.
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 Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
10/24/20151 Chapter 2 Review: MATLAB Environment Introduction to MATLAB 7 Engineering 161.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
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.
Beginning Programming for Engineers Introduction to Programming and Computer Science.
Chapter 3 MATLAB Fundamentals Introduction to MATLAB Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
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.
Working with Arrays in MATLAB
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
EGR 115 Introduction to Computing for Engineers User-Defined Functions1 – Part 1 Wednesday 22 Oct 2014 EGR 115 Introduction to Computing for Engineers.
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.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Introduction to programming Carl Smith National Certificate Year 2 – Unit 4.
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Chapter 6 Methods Chapter 6 - Methods.
1 Lecture 3 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Program design and algorithm development We will consider the design of your own toolbox to be included among the toolboxes already available with your.
ENG College of Engineering Engineering Education Innovation Center 1 Functions 1 in MATLAB Topics Covered: 1.Uses of Functions Organizational Tool.
Chapter 4 MATLAB Programming MATLAB Troubleshooting Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
PROGRAMMING FUNDAMENTALS INTRODUCTION TO PROGRAMMING. Computer Programming Concepts. Flowchart. Structured Programming Design. Implementation Documentation.
1-2 What is the Matlab environment? How can you create vectors ? What does the colon : operator do? How does the use of the built-in linspace function.
Lecture 1: Introduction
Use of Mathematics using Technology (Maltlab)
Introduction to MATLAB
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
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.
Polar Coordinates Polar and Rectangular Coordinates
Presentation transcript:

November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB

November 1, 2005 Lecture 12 - By Paul Lin 2 User-Defined M-File Functions 12-1 Intro to MATLAB Functions 12-2 Variable Passing (By Value)

November 1, 2005 Lecture 12 - By Paul Lin 3 User-Defined M-File Functions Past 30-years Programming Practices Past 30-years Programming Practices ReuseReuse PortabilityPortability ReliabilityReliability MaintainabilityMaintainability Programming Language and Practices Programming Language and Practices Modular (Structured) Programming (1970 to late 1980s) – Fortran, C, Ada; (MATLAB 1990 – present)Modular (Structured) Programming (1970 to late 1980s) – Fortran, C, Ada; (MATLAB 1990 – present) Object-Oriented Programming (1990s) – SmallTalk, C++, JavaObject-Oriented Programming (1990s) – SmallTalk, C++, Java Component-Based Programming (2000s) – C#, or.NETComponent-Based Programming (2000s) – C#, or.NET

November 1, 2005 Lecture 12 - By Paul Lin 4 User-Defined M-File Functions MATLAB Programming Language Features (Modular and Structured) MATLAB Programming Language Features (Modular and Structured) Top-down design – Module and subtasksTop-down design – Module and subtasks Independent testing of function-level sub-tasks - maintainabilityIndependent testing of function-level sub-tasks - maintainability Reuse – reusability thorough packaging of functions, reduce programming efforts and increasing productivityReuse – reusability thorough packaging of functions, reduce programming efforts and increasing productivity Isolation from unintended side effects – reliability through data hiding, separate workspace for each function to avoid certain mistakesIsolation from unintended side effects – reliability through data hiding, separate workspace for each function to avoid certain mistakes

November 1, 2005 Lecture 12 - By Paul Lin 5 Introduction to MATLAB Functions Types of M-File Functions Types of M-File Functions MATLAB Built-In Functions: abs(x), cos(x), sin(x), max(x)MATLAB Built-In Functions: abs(x), cos(x), sin(x), max(x) User-Defined M-File Functions (increase code re-usability)User-Defined M-File Functions (increase code re-usability) Functions Functions Subroutines or Procedures (providing services)Subroutines or Procedures (providing services) Function name, arguments, return arguments list (values)Function name, arguments, return arguments list (values) Function CallsFunction Calls Function M File Input Data Output Data

November 1, 2005 Lecture 12 - By Paul Lin 6 Introduction to MATLAB Functions MATLAB Function Format MATLAB Function Format function [out_arg1, out_arg2, …] = function_name(in_arg1, in_arg2, …) % Comments lines % More comments Executable codes (return) -- Optional (end) -- For version 7.0 and newer

November 1, 2005 Lecture 12 - By Paul Lin 7 MATLAB Built-In Functions Toolbox\matlab\ Toolbox\matlab\ elefun folder (elementary functions)elefun folder (elementary functions) elemat folder (elementary matrix function)elemat folder (elementary matrix function) general foldergeneral folder etcetc

November 1, 2005 Lecture 12 - By Paul Lin 8 MATLAB Built-In Functions \toolbox\matlab\elefun \toolbox\matlab\elefun Elementary Math Functions Elementary Math Functions abs.mabs.m exp.mexp.m cos.mcos.m sin.msin.m pow.mpow.m

November 1, 2005 Lecture 12 - By Paul Lin 9 MATLAB fliplr Function function y = fliplr(x) %FLIPLR Flip matrix in left/right direction. % FLIPLR(X) returns X with row preserved and columns flipped % in the left/right direction. % % X = becomes % % % See also FLIPUD, ROT90, FLIPDIM. % Copyright The MathWorks, Inc. % $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $ if ndims(x)~=2, error('X must be a 2-D matrix.'); end [m,n] = size(x); y = x(:,n:-1:1); Return value Error Checking An Example 8-line Help Comments

November 1, 2005 Lecture 12 - By Paul Lin 10 fliplr Function If x = [1 2 3; 4 5 6]; or = = [m,n] = size(x) m= 2, n = 3 y = x(:,n:-1:1); y = x(:,n:-1:1); x(:, -- All rows remain unchanged x(:, -- All rows remain unchanged n:-1:1 -- Colon operator to access column elements n:-1:1 -- Colon operator to access column elements The meaning of first n is to copy the column-n of the x array, into the column-1 of the y arrayThe meaning of first n is to copy the column-n of the x array, into the column-1 of the y array The meaning of the :1 is to copy the column 1 of x into the very last column of yThe meaning of the :1 is to copy the column 1 of x into the very last column of y The meaning of the :-1 is to copy column n-1 of x into column n-1 of y; then decrement the column by -1 to copy the column n-2 of x into the column-2 of y; until all columns between n and 1 are copied.The meaning of the :-1 is to copy column n-1 of x into column n-1 of y; then decrement the column by -1 to copy the column n-2 of x into the column-2 of y; until all columns between n and 1 are copied. y =

November 1, 2005 Lecture 12 - By Paul Lin 11 View fliplr Function >> dbtype fliplr 1 function y = fliplr(x) 2 %FLIPLR Flip matrix in left/right direction. 3 % FLIPLR(X) returns X with row preserved and columns flipped 4 % in the left/right direction. 5 % 6 % X = becomes % % 9 % See also FLIPUD, ROT90, FLIPDIM % Copyright The MathWorks, Inc. 12 % $Revision: 5.9 $ $Date: 2002/04/08 20:21:05 $ if ndims(x)~=2, error('X must be a 2-D matrix.'); end 15 [m,n] = size(x); 16 y = x(:,n:-1:1);

November 1, 2005 Lecture 12 - By Paul Lin 12 Example 1 A User-Define Function Example Phases of Function Development - Designing phase - Coding phase - Testing Phase - Release and Implementation The Desired Function Calculating the Hypotenuse Calculating the Hypotenuse Hypotenuse – the side of a right- triangle that is opposite the right angle (domain knowledge) Hypotenuse – the side of a right- triangle that is opposite the right angle (domain knowledge) Function name – hypotenuse Function name – hypotenuse Input arguments – a, b Input arguments – a, b Output arguments – h Output arguments – h The function hypotenuse.m The function hypotenuse.m function h = hypotenuse(a, b) h = sqrt(a.^2 + b.^2); A BC AC - Hypotenuse h a b

November 1, 2005 Lecture 12 - By Paul Lin 13 Example 1 A User-Define Function Example Code the hyotense.m M-file function and save it under cpet190/codes folder Code the hyotense.m M-file function and save it under cpet190/codes folder Run the function: Click on Debug -> Run Run the function: Click on Debug -> Run Error message shows Error message shows

November 1, 2005 Lecture 12 - By Paul Lin 14 Example 1 A User-Define Function Example Testing Functions: Testing Functions: First Testing: First Testing:hypotense(3,4) Second Testing: Second Testing: a = 3, b =4; a = 3, b =4; hypotenuse(a,b) hypotenuse(a,b) Third Testing: Third Testing: side_a = 3; side_b = 4; side_a = 3; side_b = 4; c = hypotenuse(side_a, side_b) c = hypotenuse(side_a, side_b)

November 1, 2005 Lecture 12 - By Paul Lin 15 Variable Passing (By Value) MATLAB programs communicate with their functions – values passing for both arrays and scalars MATLAB programs communicate with their functions – values passing for both arrays and scalars Make a copy of the actual arguments and passes them to the function Make a copy of the actual arguments and passes them to the function Service requesting function cannot modify the actual arguments Service requesting function cannot modify the actual arguments

November 1, 2005 Lecture 12 - By Paul Lin 16 Example 2 Parallel Resistance Function for calculating Parallel resistance Function for calculating Parallel resistance Domain Knowledge: Domain Knowledge: Req = R1 || R2 = (R1 * R2)/(R1 + R2) Function design Function design function Req = p_rs(r1, r2) function Req = p_rs(r1, r2) % Comments % if r1 < 0 Req = -1; Req = -1; elseif r2 < 0 Req = -1; Req = -1; elseif (r1 == 0) || (r2 == 0) Req = 0; Req = 0;else Req = (r1 * r2)/(r1 + r2) Req = (r1 * r2)/(r1 + r2)end

November 1, 2005 Lecture 12 - By Paul Lin 17 Example 2 Parallel Resistance Coding Coding Documentation Documentation PurposesPurposes Calling sequenceCalling sequence Defining VariablesDefining Variables Record of revisionsRecord of revisions Testing Testing p_rs(10,10) -- 5 ohmsp_rs(10,10) -- 5 ohms p_rs(10, p_rs(20,20)) – 5 ohmsp_rs(10, p_rs(20,20)) – 5 ohms p_rs(ra, rb)p_rs(ra, rb)

November 1, 2005 Lecture 12 - By Paul Lin 18 Example 3 Rectangular-to-Polar Conversion Problem Statement Problem Statement The location of a point in a cartesian plane can be expressed in either the rectangular coordinates(x,y) or the polar coordinates(r, theta) as shown on the slide.The location of a point in a cartesian plane can be expressed in either the rectangular coordinates(x,y) or the polar coordinates(r, theta) as shown on the slide. The point P(x,y) or P(r, theta)The point P(x,y) or P(r, theta) Two functions for converting between rectangular coordinate polar coordinateTwo functions for converting between rectangular coordinate polar coordinate

November 1, 2005 Lecture 12 - By Paul Lin 19 Example 3 Rectangular-to-Polar Conversion Domain Knowledge Domain Knowledge x = r cos(theta) y= r sin(theta) r = sqrt(x^2 + y^2) theta = tan -1 (y/x) Define the function’s name, inputs and outputs Define the function’s name, inputs and outputs function [x, y] polar2rect(r, theta) function [r, theta] rect2polar(x,y) Convert equations to MATLAB statement Convert equations to MATLAB statement Code and test function Code and test function Add documentation to the two functions Add documentation to the two functions

November 1, 2005 Lecture 12 - By Paul Lin 20 Example 3 Rectangular-to-Polar Conversion The two functions The two functions function [x, y] = polar2rect(r, theta) x = r * cos(theta*pi/180); y = r * sin(theta*pi/180); end

November 1, 2005 Lecture 12 - By Paul Lin 21 Example 3 Rectangular-to-Polar Conversion The two functions The two functions function [r, theta] = rect2polar(x,y) %ATAN2 Four quadrant inverse tangent. % ATAN2(Y,X) is the four quadrant arctangent of the % real parts of the elements of X and Y. % -pi <= ATAN2(Y,X) <= pi. r = sqrt(x^2 + y^2); theta = (180/pi)* atan2(y,x); end

November 1, 2005 Lecture 12 - By Paul Lin 22 Example 3 Rectangular-to-Polar Conversion Testing Functions Testing Functions >> [x, y] = polar2rect(5, ) x = y = >> [x, y] = polar2rect(5, ) x = y = Testing Functions Testing Functions >> [r, theta] = rect2polar(4,3) r = 5 theta = >> [r, theta] = rect2polar(-4,-3) r = 5 theta =

November 1, 2005 Lecture 12 - By Paul Lin 23 Summary Intro to MATLAB Functions Intro to MATLAB Functions Variable Passing (By Value) Variable Passing (By Value) Example 1 – Function for Hypotenuse calculation Example 1 – Function for Hypotenuse calculation Example 2 – Function for Parallel Resistance computation Example 2 – Function for Parallel Resistance computation Example 3 – Function for rectangular to polar conversion Example 3 – Function for rectangular to polar conversion