MATLAB 입문 CHAPTER 3 Functions and Files • Note: Class presentation slides from 2016 MATLAB Course • Provided by Prof. Poogyun Park, EE Department, POSTECH SPaC, POSTECH 1 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Elementary Mathematical Functions lookfor : find functions that are relevant to your application help : when you know the correct spelling of the function 2 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Exponential and Logarithmic Functions Complex Some common mathematical functions Exponential exp(x) Exponential; sqrt(x) Square root; e x abs(x) Absolute value; x angle(x) Angle of a complex number x conj(x) Complex conjugate imag(x) Imaginary part of a complex number x real(x) Real part of a complex number x Numeric ceil(x) Round to the nearest integer toward fix(x) Round to the nearest integer toward zero. floor(x) Round to the nearest integer toward round(x) Round toward nearest integer sign(x) Signum function: +1 if x> 0; if x = 0; -1 if x < 0 x Logarithmic log(x) Natural logarithm; ln x log10(x) Common(base10) logarithm; log(x) means ln x. 3 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Complex Number Functions(1/2) rectangular representation a + ib polar representation Mθ abs(x), angle(x) absolute value (magnitude) angle conj(x) complex conjugate 4 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Complex Number Functions(2/2) 5 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Numeric Functions MATLAB has been optimized to deal with arrays. round(y) : rounds to the nearest integer ans = 2, 3, 4 fix(y) : truncates to the nearest integer toward zero ans = 2, 2, 3 ceil(y) : rounds to the nearest integer toward ∞ ans = 3, 3, 4 e.g. z = [-2.6 , -2.3 , 5.7] floor(z) : rounds to the nearest integer toward - ∞ ans = -3, -3, 5 fix(z) = -2, -2, 5 abs(z) = 2.6 , 2.3, 5.7 6 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Trigonometric Functions Table 3.1-2 Trigonometric functions Trigonometric Inverse trigonometric acos(x) Inverse cosine; 1 arccos x = cos x acot(x) Inverse cotangent; 1 arccot x = cot x acsc(x) Inverse cosecant; 1 arccsc x = csc x asec(x) Inverse secant;1 arcsec x = sec x asin(x) Inverse sine; arcsin x = si n1x atan(x) Inverse tangent; arctan x = tan1x atan2(y,x) four-quadrant inverse tangent. *angle : radian cos(x) Cosine; cos x. cot(x) Cotangent; cot x. csc(x) Cosecant; csc x. sec(x) Secant; sec x. sin(x) Sine; sin x. tan(x) Tangent; tan x. 7 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Hyperbolic Functions(1/2) Hyperbolic functions Hyperbolic (ex e x )/2 cosh(x) Hyperbolic cosine; cosh x = coth(x) Hyperbolic cotangent; cosh x / sinh x csch(x) Hyperbolic cosecant; 1 / sinh x sech(x) Hyperbolic secant; 1 / cosh x sinh(x) Hyperbolic sine; sinh x = tanh(x) Hyperbolic tangent; sinh x / cosh x (ex e x )/2 8 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Hyperbolic Functions(2/2) Hyperbolic functions Inverse hyperbolic acosh (x) Inverse hyperbolic cosine; acoth (x) Inverse hyperbolic cotangent; coth1x 1 l n(x 1), x 1 o r x 1 cosh1x l n(x x 2 1), x 1 2 acsch (x) Inverse hyperbolic cosecant; asech (x) Inverse hyperbolic secant; asinh (x) Inverse hyperbolic sine; atanh (x) Inverse hyperbolic tangent; x -1 1 1 csch1x l n ( 1), x 0 x x2 1 1 se ch1x l n ( 1), 0 x 1 x x2 si nh1x l n(x x 2 1), - x tanh1x 1 1 x l n( ), 1 x 1 2 1- x 9 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH User-Defined Functions(1/4) Function file : when need to repeat a set of commands several times. variables : local syntax function [output variables] = function_name (input variables) function_name = saved file name ( with the .m extension) function_name = drop : file name = drop.m e.g. 10 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH User-Defined Functions(2/4) e.g. 11 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH User-Defined Functions(3/4) the order of arguments is important, not the names of the arguments use arrays as input arguments 12 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH User-Defined Functions(4/4) more than one output 13 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Variations in the Function Line Function definition line File name 1. function [area_square] = square(side); square.m 2. function area_square = square(side); square.m 3. function [volume_box] = box(height,width,length); box.m 4. function [area_circle, circumf] = circle(radius); circle.m 5. function sqplot(side); sqplot.m 14 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Local Variables, Global Variables Local variables variables created by a function file are local to that function. local : their values are not available outside the function. Global variables their values are available to the basic workspace and to other functions that declare these variables global. variables in script file : global 15 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Minimization and root-finding functions Table 3.2-1 Minimization and root-finding functions Function Description fminbnd(‘function’,x1,x2) Returns a value of x in the interval x1≤x ≤x2 that corresponds to a minimum of the single-variable function described by the string ‘function’. fminsearch(‘function’,x0) Uses the starting vector x0 to find a minimum of the multivariable function described by the string ‘function’. fzero(‘function’,x0) Uses the starting value x0 to find a zero of the single-variable function described by the string ‘function’. 16 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Advanced Function Programming Function Handles using the at sign : @ e.g. >> sine_handle = @sin; >> plot([0:0.01:6], sine_handle(0: 0.01: 6)) function x = gen_plot(fun_handle, interval) plot(interval, fun_handle, interval) >>gen_plot(sine_handle, [0: 0.01: 6]) or >>gen_plot(@sin, [0: 0.01: 6]) advantages speed of execution and providing access to subfunctions. a standard MATLAB data type, and thus can be used in the same manner as other data types. 17 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Methods for Calling Functions four ways to invoke, or “call,” a function into action. 1. As a character string identifying the appropriate function M-file. function y = fun1(x) y = x.^2-4; >>[x, value] = fzero(‘fun1’,[0,3]) 2. As a function handle. >>[x, value] = fzero(@fun1,[0,3]) 3. As an “inline” function object, or >>fun1 = ‘x.^2-4’; >>fun_inline = inline(fun1); >>[x, value] = fzero(fun_inline, [0,3]) 4. As a string expression. >>fun1 = ‘x.^2-4’; >>[x, value] = fzero(fun1, [0,3]) >>[x, value] = fzero(‘x.^2-4’, [0,3]) or as 18 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Types of Functions(1/2) primary functions contains the main program. the only function that you can call from the MATLAB command line or from another M-file function anonymous functions create a simple function without needing to create an M-file for it. provide a quick way of making a function from any MATLAB expression subfunctions placed in the primary function use multiple functions within a single primary function M-file 19 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Types of Functions(2/2) nested functions defined within another function help to improve the readability of your program difference between nested functions and subfuntions: subfunctions normally cannot be accessed outside of their primary function fle overloaded functions functions that respond differently to different types of input arguments. created to treat integer inputs differently than inputs of class double. private functions restrict access to a function called only from an M-file function in the parent directory 20 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Anonymous Functions create a simple function without needing to create an M-file for it. MATLAB command line from within another function or script syntax fhandle = @(arglist) expr arglist: a comma-separated list of input arguments to be passed to the function expr: any single, valid MATLAB expression e.g. sq = @(x) x.^2; >>sq(5) >>ans = 25 >>sq([5,7]) >>ans = 25 49 be useful for more complicated functions involving numerous keystrokes. 21 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Variables and Anonymous Functions variables can appear in anonymous functions in two ways as variables specified in the argument list e.g. f = @(x) x.^3; as variables specified in the body of the expression e.g. plane = @(x, y) A*x + B*y; 22 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Subfunctions(1/2) all other functions in the primary function are called subfunctions. the order for checking functions in MATLAB 1. checks to see if the function is a built-in function such as sin. 2. checks to see if the function is subfunction in the file. 3. checks to see if the function is private function. may use subfunctions with the same name as another existing M-file. allow you to name subfunctions without being concerned about whether another function exists with the same name protects you from using another function unintentionally 23 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Subfunctions(2/2) e.g. function y = subfun_demo(a) primary function y = a – mean(a); subfunction % function w = mean(x) w = sqrt(sum(x.^2))/length(x); a sample session follows. >> y =subfun_demo([4,-4]) y= 1.1716 -6.8284 if had used the MATLAB M-function mean different answer >> a= [4, -4]; >> b =a – mean(a) b= 4 -4 24 SPaC, POSTECH MATLAB 입문 : Chapter 1. An Overview of MATLAB Nested Functions(1/2) Functions that are defined within the main function. contains the usual components of an M-file function. must always terminate with an end statement. e.g. function f = parabola(a, b, c) f =@p; function y = p(x) y = a*x^2 + b*x + c; end end In the command window type >>f = parabola(4, -50, 5); >>fminbnd(f, -10, 10) ans = 6.2500 6.2500 25 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Nested Functions(2/2) two unique properties 1. can access the workspace of all functions inside of which it is nested. 2. function handle stores the information needed to access the nested function stores the values of all variables shared between the nested function and those functions that contain it call a nested function 1. from the level immediately above it 2. from a function nested at the same level within the same parent function 3. from a function at any lower level 26 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Private Functions reside in subdirectories with the special name private. visible only to functions in the parent directory. invisible outside the parent directory. MATLAB looks for private functions before standard M-file functions. 27 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Working with Data Files header : a comment that describe what the data represent, the date it was created, and who created the date. Importing data : bring data created by other applications into the MATLAB workspace. Exporting data : package workspace variables so that they can be used by other applications. Importing Wizard : a graphical user interface 28 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH Importing Data from Externally Generated Files ASCII file format if the file has a header or the data is separated by commas, MATLAB will produce an error message. to correct load the data file into a text editor remove header replace the commas with spaces type load filename to retrieve the data into MATLAB e.g. if the data file name is force.dat type load force.dat Importing Spreadsheet Files file format : .wk1 command : M = wk1read(‘filename’) Microsoft Excel workbook file .xls A = xlsread(‘filename’) 29 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH The Import Wizard(1/5) To import ASCII data 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 is, the character used to separate the data items in each row? The delimiter is also called the column separator. The data format will usually fall into one of the following categories 1.Space-delimited ASCII data files, 2.Mixed text and numeric ASCII data files, 3.ASCII data files with text headers, or 4.ASCII data files with nonspace delimiters (usually semicolons). 30 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH The Import Wizard(2/5) The import Wizard present a series of dialog boxes in which you: 1. Specify the name of the file you want to import, 2. Specify the delimiter used in the file, and 3. Select the variables that you want to import Note when you use the Import Wizard to create a variable in the MATLAB workspace, it overwrites any existing variable in the workspace with the same name without issuing a warning. 31 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH The Import Wizard(3/5) e.g. 32 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH The Import Wizard(4/5) e.g. 33 MATLAB 입문 : Chapter 1. An Overview of MATLAB SPaC, POSTECH The Import Wizard(5/5) e.g. 34