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

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
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.
MATLAB & Its Applications In Engineering 胡章芳
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
Linear Filtering – Part I Selim Aksoy Department of Computer Engineering Bilkent University
Functions Scripts and Workspace scripts are just a collection of commands, running a script is same as running the statements in command window. Your.
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;
A Brief Introduction to MATLAB Shibaji Shome and Rob MacLeod CVRTI University of Utah.
MATLAB Review Selim Aksoy Bilkent University Department of Computer Engineering
Top-down Program Design, Relational and Logical Operators
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
User-defined Functions Selim Aksoy Bilkent University Department of Computer Engineering
Input/Output Functions Selim Aksoy Bilkent University Department of Computer Engineering
Top-down Program Design Selim Aksoy Bilkent University Department of Computer Engineering
Program Design, Relational and Logical Operators Selim Aksoy Bilkent University Department of Computer Engineering
General Computer Science for Engineers CISC 106 Lecture 26 Dr. John Cavazos Computer and Information Sciences 04/24/2009.
Introduction to LabVIEW Seth Price Department of Chemical Engineering New Mexico Tech Rev. 10/5/14.
Introduction to MATLAB
MATLAB Strings Selim Aksoy Bilkent University Department of Computer Engineering
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.
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.
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.
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.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
Advanced Topics- Functions Introduction to MATLAB 7 Engineering 161.
Introduction to Computer Programming
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.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
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.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
EGR 115 Introduction to Computing for Engineers MATLAB Basics 6: Debugging in MATLAB Monday 15 Sept 2014 EGR 115 Introduction to Computing for Engineers.
1 Lecture 4 Post-Graduate Students Advanced Programming (Introduction to MATLAB) Code: ENG 505 Dr. Basheer M. Nasef Computers & Systems Dept.
Interduction to MATLAB (part 2) Manal Alotaibi Mathematics department College of science King saud university.
CS112 Scientific Computation Department of Computer Science Wellesley College Storing Values for Safe Keeping Variables and their Values.
Introduction to Programming on MATLAB Ecological Modeling Course Sep 11th, 2006.
Matlab Programming for Engineers
Introduction to Matlab
1-1 Logic and Syntax A computer program is a solution to a problem.
CS005 Introduction to Programming
What’s cheating and what is not?
Chapter 9 Recursion.
Introduction to Programming for Mechanical Engineers
Basic operations in Matlab
Lecture 1: Introduction
Matlab review Matlab is a numerical analysis system
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
MATLAB – What Is It ? Name is from matrix laboratory Powerful tool for
Writing functions in MATLAB
MATLAB – What Is It ? Name is from matrix laboratory Powerful tool for
Algorithms Take a look at the worksheet. What do we already know, and what will we have to learn in this term?
Computer Science Word Wall
CSCI N317 Computation for Scientific Applications Unit 1 – 1 MATLAB
Hacettepe University Computer Engineering Department
Experiment No. (1) - an introduction to MATLAB
Using Script Files and Managing Data
CSE 1020:Software Development
QTP Test Process
CPS125.
MATLAB (Lecture 2) BY:MAHA ALMOUSA.
Redundant code repositories
Computer Simulation Lab
ME 123 Computer Applications I Lecture 5: Input and Output 3/17/03
Electrical and Computer Engineering Department SUNY – New Paltz
Presentation transcript:

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

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

Fall 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

Fall 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

Fall 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

Fall 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

Fall 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

Fall 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

Fall 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....

Fall 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);

Fall 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

Fall 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

Fall 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

Fall 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

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

Fall 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. % 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); % And calculate angle in degrees. angle = atan2(y,x) * 180/pi;

Fall 2004CS Function Examples function [avg, med] = mystats(u) %MYSTATS Find mean and median. % Function MYSTATS calculates the average and median % of a data set. n = length(u); % Calculate average. avg = sum(u)/n; % Calculate median. w = sort(u); if rem(n,2) == 1 med = w((n+1)/2); else med = ( w(n/2) + w(n/2+1) ) / 2; end

Fall 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