Functions: Matlab Tutorial PDF
Document Details

Uploaded by SafeSavanna7008
Anthony Mile
Tags
Summary
This document is a tutorial about functions in Matlab by Dr Anthony Mile. It covers topics such as user-defined functions, anonymous functions, and linear solving. Key Matlab concepts such as syntax are described, along with examples.
Full Transcript
Functions By Dr. Anthony Mile CUK What is a Function? A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files (m-files). The name of the file and of the function should be the same. Functions operate on variables withi...
Functions By Dr. Anthony Mile CUK What is a Function? A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files (m-files). The name of the file and of the function should be the same. Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace. Functions can accept more than one input arguments and may return more than one output arguments. Types: User defined functions, Anonymous functions, Recursive functions Basic m-file Functions Properties of basic function m-files: 1. Function name is the same as the name of the m-file. 2. The function can have many input parameters and many output parameters. input parameters take on the values given by the calling function. output parameters have values that are returned to the calling function. 3. Variables in the function have their own workspace (memory). Variables in the function are separate from variables in other functions and in the command window environment, even if those variables have the same names. Values are only shared via input and output parameters. User-Defined Functions Is a Matlab program that is created by the user, saved as a function file, and then can be used like a built-in function. A function in general has input arguments (or parameters) and output variables (or parameters) that can be scalars, vectors, or matrices of any size. There can be any number of input and output parameters, including zero. Calculations performed inside a function typically make use of the input parameters, and the results of the calculations are transferred out of the function by the output parameters. Basic parts of a function M-file Writing a Function File A function file can be written using any text editor (including the Matlab Editor). The file must be in the Matlab Path in order for Matlab to be able to locate the file. The first executable line in a function file must be the function definition line, which must begin with the keyword function. The most general syntax for the function definition line is: function [out1, out2,...] = functionName(in_1, in2,...) where "functionName" is the name of the user-defined function, in1, in2,... are the input parameters, and out1, out2,... are the output parameters. The parentheses are needed even if the function has no input parameters: function [out1, out2,...] = functionName( ) If there is only one output parameter, then the square brackets can be omitted: function out = functionName(in1, in2,...) If there is no output parameter at all, then they are called void functions. i.e. a function that does not return a value, but instead plots something on a given interval. The function definition line is written as: function functionName(in1, in2,...) Example: function myfun(a,b) And call it with: plot(a:b) myfun(1,7) The first comment line in the function file is referred to as the H1 line. Make sure that the H1 line contains important keywords that adequately describe the function. Because when a user types lookfor myfun on the Command line, Matlab searches for myfun in the H1 lines of all the functions, and if a match is found, the name of the function file as well as the H1 line that contains the match is displayed. A user-defined function is used in the same way as a built-in function. The function can be called from the Command line, from a script file, or from another function (including itself). A function that calls itself is referred to as a recursive function. Basic m-file Function: Example The quadraticRoots function is contained in quadraticRoots.m and can be called from the command line, or another m-file. Function Input and Output twosum.m function twosum(x,y) % twosum Add two matrices % and print the result x+y end threesum.m function s = threesum(x,y,z) % threesum Add three variables % and return the result s = x+y+z; end addmult.m function [s,p] = addmult(x,y) % addmult Compute sum and product % of two matrices The last statement produces no s = x+y; output because the assignment p = x*y; expression ends with a semicolon. end The value of 24 is stored in b. User-defined Function - Example Write a function, call it “max”, that takes five numbers as argument and returns the maximum of the numbers. The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers. function max = mymax(n1, n2, n3, n4, n5) %This function calculates the maximum of the % five numbers given as input max = n1; if(n2 > max) max = n2; end if(n3 > max) max = n3; end if(n4 > max) max = n4; end You can call the function as − if(n5 > max) max = n5; mymax(34, 78, 89, 23, 11) end You can also use that function to return entire matrices. For example, the commands: will produce the graph: Print figure to eps format Anonymous Functions (1) Is a simple, typical a single line, user-defined function that is defined and written within the computer code (not in a separate file) and is then used in the code. They have only a one-line executable statement. They do not have either “function” or “end” statement Use a special @(x) syntax. They can be defined in any part of MATLAB (in the Command Window, in script files, and inside regular user-defined functions). An anonymous function is created by typing the following statement: functionName = @ (var1, var2,...) expression where 'functionName' is the name of the anonymous function, 'var1', 'var2', etc. are a comma separated list of arguments of the function, and 'expression' is a single mathematical expression involving those variables. Anonymous Functions (2) Pass Function to Another Function Can use anonymous functions You can pass a handle to an anonymous function to function functions An anonymous function is a one-line expression-based MATLAB® function that does not require a program file. 𝑥 For example, evaluate the integral of −1 on the range [0,Inf]: ⅇ𝑥 −1 fun = @(x)x./(exp(x)-1); q4 = integral(fun,0,Inf) Nested Functions Are functions within the body of another function. Nested functions are defined within the scope of another function and they share access to the containing function's workspace. A nested function follows the following syntax function x = A(p1, p2)... B(p2) Function y = B(p3)... end... end Program decomposition/Linear Solving decomposition creates reusable matrix decompositions that enable you to solve linear systems (Ax = b or xA = b) more efficiently. This single matrix equation is used to express a system of equations where A and b are matrices (b could be a vector, as a special case) and that you want to find a solution x. For example, after computing dA = decomposition(A) the call dA\b returns the same vector as A\b, but is typically much faster. decomposition objects are well- suited to solving problems that require repeated solutions, since the decomposition of the coefficient matrix does not need to be performed multiple times. You can use a decomposition object dA with many of the same operators you might use on the original coefficient matrix A: Complex conjugate transpose dA' Negation -dA Multiply or divide by a scalar using c*dA or dA/c. Solve a linear system Ax = b using x = dA\b. Solve a linear system xA = b using x = b/dA. Example – Linear Equations 1. Solve below linear equation using MATLAB 2α + 8β + γ + 3δ = 100 α + β + 9γ + 7δ = 143 4α + 9β + γ + 5δ = 111 4α + 8β + 8γ + 2δ = 264 A = [2 8 1 3; 1 1 9 7; 4 9 1 5; 4 8 8 2]; B=[100;143;111;264]; = [2 8 1 3; 1 1 9 7; 4 9 1 5; 4 8 8 2] [α; β; γ; δ] = [100;143;111;264]; X= [α; β; γ; δ] = Aˉ¹B = Inv(A)*B X = Linsolve (A,B) (where X = α; β; γ; δ)