User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering

Slides:



Advertisements
Similar presentations
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Advertisements

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.
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
MATLAB Functions – Part II Greg Reese, Ph.D Research Computing Support Group Academic Technology Services Miami University September 2013.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 19P. 1Winter Quarter MATLAB: Script and.
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;
Additional Data Types: 2-D Arrays, Logical Arrays, Strings Selim Aksoy Bilkent University Department of Computer Engineering
11.3 Function Prototypes A Function Prototype contains the function’s return type, name and parameter list Writing the function prototype is “declaring”
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Top-down Program Design, Relational and Logical Operators
EGR 106 – Week 8 Data Files & Functions Interacting with Data Files Functions – Concept – Examples and applications Textbook chapter ,
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
Top-down Program Design Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Program Design, Relational and Logical Operators 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.
MATLAB Programming fprintf Cell arrays Structures Flow of control Vectorization Functions 1.
Introduction to MATLAB
Additional Data Types: Strings Selim Aksoy Bilkent University Department of Computer Engineering
MATLAB Strings Selim Aksoy Bilkent University Department of Computer Engineering
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.
1 MATLAB 基礎. 2 MATLAB  Workspace: environment (address space) where all variables reside  After carrying out a calculation, MATLAB assigns the result.
January 24, 2005 Lecture 3 - By P. Lin 1 CPET 190 Lecture 3 Problem Solving with MATLAB
M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files called M- files. M-files are.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
November 1, 2005 Lecture 12 - By Paul Lin 1 CPET 190 User Defined Functions Lecture 12 Problem Solving with MATLAB
1 Advanced MATLAB Vectors and matrices fprintf Cell arrays Structures Flow of control Vectorization Functions.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
A First Book of ANSI C Fourth Edition
Matlab Programming for Engineers Dr. Nidal Farhat Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Copyright © The McGraw-Hill Companies, Inc. Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 1 An Overview of MATLAB.
A Brief introduction to MatLAB ($50 - $99 for students)
SUNY-New Paltz Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz “Lecture 6”
Functions CS 103 March 3, Review A function is a set of code we can execute on command to perform a specific task A function is a set of code we.
Functions CS 103. Review A function is a set of code we can execute on command to perform a specific task When we call a function, we can pass arguments.
Digital Image Processing Lecture10: MATLAB Example – Utility M-functions for Intensity Transformations.
1 MatLab Basics Jae Hoon Kim Department of Physics Kangwon National University It contains hundreds of commands to do mathematics. Graph functions, solve.
Flow Control and Functions ● Script files ● If's and For's ● Basics of writing functions ● Checking input arguments ● Variable input arguments ● Output.
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.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 6 Review: User Defined Functions Introduction to MATLAB 7 Engineering 161.
ENG College of Engineering Engineering Education Innovation Center 1 More Script Files in MATLAB Script File I/O : Chapter 4 1.Global Variables.
Recap Saving Plots Summary of Chapter 5 Introduction of Chapter 6.
CSE123 Lecture 3 Files and File ManagementScripts.
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.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Digital Image Processing Introduction to M-function Programming.
MATLAB for Engineers, by Holly Moore. ISBN © 2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Introduction to Matlab Patrice Koehl Department of Biological Sciences National University of Singapore
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
Introduction to Programming Python Lab 5: Strings and Output 05 February PythonLab5 lecture slides.ppt Ping Brennan
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
SCRIPTS AND FUNCTIONS DAVID COOPER SUMMER Extensions MATLAB has two main extension types.m for functions and scripts and.mat for variable save files.
Scripts & Functions Scripts and functions are contained in .m-files
User Defined Functions
Computational Methods 2018/2019 Fall Chapter 2-B
Presentation transcript:

User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering

Summer 2004CS 1112 Scripts Command window: x = 2; my_script Hello! y = x + 2 y = 7 my_script.m: disp( 'Hello' ); x = 5;

Summer 2004CS 1113 Scripts A script is just a collection of MATLAB statements Running a script is the same as running the statements in the command window Scripts and the command window share the same set of variables, also called global variables

Summer 2004CS 1114 Workspace Workspace is the collection of variables that can be used when a command is executing Scripts and the command window share the same workspace Global variables are problematic because values you depend on may be changed by other scripts

Summer 2004CS 1115 Functions A function is a black box that gets some input and produces some output We do not care about the inner workings of a function Functions provide reusable code Functions simplify debugging Functions have private workspaces The only variables in the calling program that can be seen by the function are those in the input list The only variables in the function that can be seen by the calling program are those in the output list

Summer 2004CS 1116 Functions function p = factorial(n) %FACTORIAL Factorial function. % FACTORIAL(N) is the product of all the integers from 1 to N, % i.e. prod(1:N). Since double precision numbers only have about % 15 digits, the answer is only accurate for N <= 21. For larger N, % the answer will have the right magnitude, and is accurate for % the first 15 digits. % % See also PROD. % Copyright The MathWorks, Inc. % $Revision: 1.5 $ if (length(n)~=1) | (fix(n) ~= n) | (n < 0) error('N must be a positive integer'); end p = prod(1:n); output argument input argument other comment lines executable code factorial.m: H1 comment line name of the function

Summer 2004CS 1117 Functions The function statement marks the beginning of a function The name of the function must be the same as the name of the m-file The lookfor command searches functions according to the H1 comment line The help command displays the comment lines from the H1 line until the first non-comment line

Summer 2004CS 1118 Function Examples function distance = dist2(x1, y1, x2, y2) %DIST2 Calculate the distance between two points % Function DIST2 calculates the distance between % two points (x1,y1) and (x2,y2) in a Cartesian % coordinate system. % Define variables: % x1 -- x-position of point 1 % y1 -- y-position of point 1 % x2 -- x-position of point 2 % y2 -- y-position of point 2 % distance -- Distance between points % Record of revisions: % Date Programmer Description of change % ==== ========== ===================== % 12/15/98 S. J. Chapman Original code % Calculate distance. distance = sqrt((x2-x1).^2 + (y2-y1).^2); four variables declared as input arguments

Summer 2004CS 1119 Function Examples help dist2 DIST2 Calculate the distance between two points Function DIST2 calculates the distance between two points (x1,y1) and (x2,y2) in a Cartesian coordinate system. lookfor distance DIST2 Calculate the distance between two points GFWEIGHT Calculate the minimum distance of a linear... DISTFCM Distance measure in fuzzy c-mean clustering....

Summer 2004CS Function Examples % Script file: test_dist2.m % % Purpose: % This program tests function dist2. % % Record of revisions: % Date Programmer Description of change % ==== ========== ===================== % 12/15/98 S. J. Chapman Original code % % Define variables: % ax -- x-position of point a % ay -- y-position of point a % bx -- x-position of point b % by -- y-position of point b % result -- Distance between the points % Get input data. disp('Calculate the distance between two points:'); ax = input('Enter x value of point a: '); ay = input('Enter y value of point a: '); bx = input('Enter x value of point b: '); by = input('Enter y value of point b: '); % Evaluate function result = dist2 (ax, ay, bx, by); % Write out result. fprintf('The distance between points a and b is %f\n',result);

Summer 2004CS Function Examples clear all x1 = 0; y1 = 5; whos Name Size Bytes Class x1 1x1 8 double array y1 1x1 8 double array Grand total is 2 elements using 16 bytes test_dist2 Calculate the distance between two points: Enter x value of point a: 1 Enter y value of point a: 1 Enter x value of point b: 4 Enter y value of point b: 5 The distance between points a and b is

Summer 2004CS Function Examples whos Name Size Bytes Class ax 1x1 8 double array ay 1x1 8 double array bx 1x1 8 double array by 1x1 8 double array result 1x1 8 double array x1 1x1 8 double array y1 1x1 8 double array Grand total is 7 elements using 56 bytes x1 x1 = 0 y1 y1 = 5

Summer 2004CS Function Examples Problem: write a function called strsearch that takes a string s and a character c, and returns the number of occurrences of c in s and the index of the first occurrence. Pseudocode: For each character of s in reverse order If character is equal to c increment the counter save the index

Summer 2004CS Function Examples function [ cnt, pos ] = strsearch( s, c ) %STRSEARCH find the number of occurrences of a character in a string % Function STRSEARCH finds the number of occurrences of a character % c in a given string s. It returns both the index of the first % occurrence and the number of occurrences. % It returns 0 for both the index and the number of occurrences if % c does not exists in s. % % By Pinar Senkul, 24/10/2003 pos = 0; cnt = 0; n = length(s); for ii = n:-1:1, if ( s(ii) == c ), cnt = cnt + 1; pos = ii; end two variables declared as output arguments

Summer 2004CS Function Examples [ a, b ] = strsearch( 'abccdecfac', 'c' ) a = 4 b = 3 a = strsearch( 'abccdecfac', 'c' ) a = 4 strsearch( 'abccdecfac', 'c' ) ans = 4

Summer 2004CS Function Examples function [mag, angle] = polar_value(x,y) %POLAR_VALUE Converts (x,y) to (r,theta) % Function POLAR_VALUE converts an input (x,y) % value into (r,theta), with theta in degrees. % It illustrates the use of optional arguments. % Check for a legal number of input arguments. msg = nargchk(1,2,nargin); error(msg); % If the y argument is missing, set it to 0. if nargin < 2 y = 0; end % Check for (0,0) input arguments, and print out % a warning message. if x == 0 & y == 0 msg = 'Both x any y are zero: angle is meaningless!'; warning(msg); end % Now calculate the magnitude. mag = sqrt(x.^2 + y.^2); % If the second output argument is present, calculate % angle in degrees. if nargout == 2 angle = atan2(y,x) * 180/pi; end optional output argument optional input argument error check for input

Summer 2004CS Functions: Optional Arguments Optional arguments can be checked using: nargchk: validates number of arguments nargin: number of input arguments nargout: number of output arguments

Summer 2004CS Function Examples [ m, a ] = polar_value ??? Error using ==> polar_value Not enough input arguments. [ m, a ] = polar_value( 1, -1, 1 ) ??? Error using ==> polar_value Too many input arguments. [ m, a ] = polar_value( 1, -1 ) m = a = -45 m = polar_value( 1, -1 ) m =

Summer 2004CS Functions: Subfunctions function [avg, med] = mystats(u) %MYSTATS Find mean and median with internal functions. % Function MYSTATS calculates the average and median % of a data set using subfunctions. n = length(u); avg = mean(u,n); med = median(u,n); function a = mean(v,n) % Subfunction to calculate average. a = sum(v)/n; function m = median(v,n) % Subfunction to calculate median. w = sort(v); if rem(n,2) == 1 m = w((n+1)/2); else m = (w(n/2)+w(n/2+1))/2; end mystats.m: main function subfunction: mean subfunction: median mystats can be called by any other MATLAB function but mean and median can only be called by other functions in the same file

Summer 2004CS Functions: Summary Both scripts and functions are saved as m-files Functions are special m-files that receive data through input arguments and return results through output arguments Scripts are just a collection of MATLAB statements Functions are defined by the function statement in the first line Scripts use the global workspace but functions have their own local independent workspaces