1 / 42

MATLAB Ch 3 – Functions & Files

MATLAB Ch 3 – Functions & Files . EGR1302. Outline. Introduction Elementary mathematical operations User-defined functions Working with data files. Introduction. Review from Ch 1 MATLAB mathematical functions Pair of parentheses after function name encloses function’s argument

nancy
Download Presentation

MATLAB Ch 3 – Functions & Files

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MATLAB Ch 3 – Functions & Files EGR1302

  2. Outline • Introduction • Elementary mathematical operations • User-defined functions • Working with data files

  3. Introduction • Review from Ch 1 • MATLAB mathematical functions • Pair of parentheses after function name encloses function’s argument • Can be part of mathematical expression • Users can define functions • MATLAB has commands and functions for managing the work session

  4. Introduction • MATLAB has many built-in functions • Users may define functions • Convenient use • Advanced function capability • Function handles • Anonymous functions • Subfunctions • Nested functions • MATLAB allows input/output of data files

  5. Section 3.1 Elementary mathematical functions

  6. Finding relevant functions • Command – lookfor • Seeks the word in the help descriptions of the MATLAB help system • If user does not know the name of function >> lookforimaginary i - Imaginary unit. j - Imaginary unit. complex - Construct complex result from real and imaginary parts. imag - Complex imaginary part.

  7. Finding relevant functions

  8. Finding relevant functions • Command – disp • If user knows correct spelling of a MATLAB function • Same output as selecting complex hyperlink after using lookfor command >> dispcomplex

  9. Tables 3.1-1, 3.1-2, 3.1-3 • List of some common mathematical functions (pp. 142, 146, 148) • Exponential & logarithmic • Complex number • Numeric • Trigonometric • Hyperbolic

  10. Example – complex functions >> x=-3+4i; >> y=6-8i; >> mag_x = abs(x) mag_x = 5 >> mag_y = abs(y) mag_y = 10 >> mag_product = abs(x*y) mag_product = 50

  11. Example – complex functions >> angle_x = angle(x) angle_x = 2.2143 >> angle_y = angle(y) angle_y = -0.9273 >> sum_angles = angle_x + angle_y sum_angles = 1.2870 >> angle_product = angle(x*y) angle_product = 1.2870

  12. Section 3.2 User-defined functions

  13. Functions files • Differences between script & functions M-files • All functions variables are local • Values available only within function • Useful when repeating a set of commands multiple times • Building blocks of larger programs • First line in function  function definition line • List of inputs and outputs

  14. Function definition line • Distinguishes function from script • function – must be lower case • Output variables must be enclosed in square brackets • Input variables must be enclosed in parentheses • func_namemust be same as name of M-file • Use exist function before naming a function function[output vars]=func_name(input vars)

  15. Simple function example function z = fun(x,y) u = 3*x; z = u + 6*y.^2; >> z = fun(3,7) z = 303 >> y = [3 4 5]; >> z = fun(y,7) z = 303 306 309 >> fun(3,7) ans = 303 >> z ??? Undefined function or variable 'z'. >> u ??? Undefined function or variable 'u'.

  16. Functions • Suppress output of function by putting semicolon after the function call • Only order of arguments is important, not names of arguments • Arrays can be used as input arguments • May have more than one output

  17. Variations in function line • One input, one output: • Brackets are optional • Two inputs, one output • One input, two outputs • No named output: function sqplot(side) function [area_square] = square(side) OR function area_square = square(side) function [volume_box] = box(height,width,length) function [area_circle,circumf] = circle(radius) function sqplot(side)

  18. 2nd simple function example function [A, C] = circle(r) A = pi*r.^2; C = 2*pi*r; >> [A, C] = circle(4) A = 50.2655 C = 25.1327 >> r = [3 4 5]; >> [A, C] = circle(r) A = 28.2743 50.2655 78.5398 C = 18.8496 25.1327 31.4159

  19. Comments in functions • Comment lines, starting with %, may be placed anywhere in function file • If user types help to obtain information about function • All comment lines immediately following function definition line up to first blank or executable line is displayed • If user types lookfor command • First comment line is displayed

  20. Local variables • Names of input variables given in function are local to the function • Other variable names can be used when calling the function • All variables inside a function are erased after the function finishes executing • Except when the same variable names appear in the output variable list used in the function call

  21. Global variables • global command declares certain variables global • Their values are available to the basic workspace and to other functions that declare these variables global. • Any assignment to those variables, in any function or in the base workspace, is available to all the other functions declaring them global. global a x q

  22. Finding the zeros of a function • function is a string containing the name of the function • x0 is a user-supplied guess for the zero • Returns a value of x that is near x0 • Identifies only points where the function crosses the x-axis • Not points where the function just touches the axis. fzero(‘function’, x0) >> fzero('cos',2) ans = 1.5708

  23. Using fzero with user-defined functions • To find the zeros of more complicated functions, it is more convenient to define the function in a function file function y = f1(x) y = x + 2*exp(-x) - 3; >> x = fzero('f1',-1) x = -0.5831 >> x = fzero('f1',2) x = 2.8887

  24. Finding the minimum of a function • function is a string containing the name of the function • Returns a value of x that minimizes the function in the interval x1 ≤ x ≤ x2 fminbnd(‘function’, x1,x2) >> fminbnd('cos', 0,4) ans = 3.1416

  25. Finding the minimum of a function • For functions of more than one variable • function is a string containing the name of the function • Vector x0 is a guess that must be supplied by the user. fminsearch(‘function’, x0) function f = f4(x) f = x(1).*exp(-x(1).^2-x(2).^2); >> fminsearch('f4',[0,0]) ans = -0.7071 0.0000

  26. Design optimization example • Example 3.2-2, p. 161

  27. Section 3.4 Working with data files

  28. Importing data files • Typical ASCII file • Header lines • One or more lines of text • Contain comments, creation date, column headings • Data • Arranged in rows & columns • Each number in a row may be separated • Spaces • Commas • Tab

  29. Importing data files • Importing an externally generated file in ASCII format • Matlab can not import data that is separated (i.e., delimited) by commas • To import a comma-delimited ASCII file, some pre-processing is required • First, open data file in a text editor (e.g., Notepad) • Second, delete the text header lines • Third, replace each comma with at least one space (i.e., use Replace function)

  30. Importing data files • Importing an externally generated file in ASCII format • Matrix is generated • Name of matrix is filename with extension stipped off • This command creates a matrix named “tensile_test” load filename load tensile_test.txt

  31. Importing data files • Excel spreadsheets may be imported into Matlab • Save Excel file in 2003 format (i.e., .xlsextension) • Imports file into array A • Imports all numeric data into array A and all text data into array B A = xlsread(‘filename’) [A, B] = xlsread(‘filename’)

  32. Import Wizard • Allows for importing a variety of ASCII file formats • Space-delimited files • Mixed text and numeric files • Files with text headers • Files with non-space delimiters • Commas • Semi-colons • Tabs

  33. Import Wizard • What you must know before you may import the data file • How many data items are in each row? • Are the data items numeric, text strings, or a mixture of both types? • Does each row or column have a descriptive text header? • What character is used as the delimiter that separates items in each row into columns?

  34. Import Wizard • Caution • Import Wizard overwrites any existing variable in the workspace with no warning message! • Dialog boxes ask you to: • Specify the name of the file you want to import • Specify the delimiter used in the file • Select the variables that you want to import

  35. Import Wizard

  36. End of Chapter 3

  37. Slides that I do not plan to use

  38. Outline • Introduction • Elementary mathematical operations • User-defined functions • Advanced function programming • Working with data files

  39. Section 3.3 Advanced function programming

  40. Function handles • Create a function handle to any function by using the at sign, @, before the function name. • Name the handle • Use the handle to reference the function • sine_handle is a user-selected name for the handle >>sine_handle = @sin;

  41. Function handles • A common use • Pass the function as an argument to another function • Example - plot sin x over 0 £x £ 6 as follows: • Cumbersome way to plot the sine function • However, the concept can be extended to create a general purpose plotting function that accepts a function as an input >>plot([0:0.01:6],sine_handle,[0:0.01:6])

  42. Function handles • function x = gen_plot(fun_handle, interval) • plot(interval, fun_handle, interval) • You may call this function to plot the sin x over 0 £x £ 6 as follows: • >>gen_plot(sine_handle,[0:0.01:6]) • or • >>gen_plot(@sin,[0:0.01:6])

More Related