GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing en.wikibooks.org — MATLAB Programming/Portable Functions - Wikibooks, open books for an open world Functions in MATLABA function is a group of sequential expression statements (a.k.a pseudo-algorithm) that are formed together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function MUST 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.
The sntax of functions as followed function [y1,...,yN] = myfunc(x1,...,xM) where syntax declares a function named myfunc that accepts inputs x1,...,xM and returns outputs y1,...,yN . Create Functions in Separate FilesTo create a new function, at "Home" tab, click on "New" ---> "Functions" It will create a template looks like the following: function [outputArg1,outputArg2] = untitled2(inputArg1,inputArg2) %UNTITLED Summary of this function goes here % Detailed explanation goes here outputArg1 = inputArg1; outputArg2 = inputArg2; end Declare a functionTo demonstrate a function usefulness, we are going to take a hypothetical situations , So, to solve the question, it might be a good time to create a custom functions to convert from Fahrenheit to Celsius . At "Home" tab, click on "New" ---> "Functions" function [Ce] = convertTemp(Fa) % Convert from Fahrenheit to Celsius Ce = (Fa-32)*(5/9); end Click on save button to save the functions as convertTemp.m file Later, on the Current Folder Panel, select the directory where you save the function files just now. Calling a functionTo call the newly created function, do the following: On the Command Window Panel, type this command as shown >> convertTemp(100) ans = 37.7778 Hence, the weather outside is almost 38 Celsius degrees. Benefits of functionsWhy this is beneficial, you might ask ? Well, from this exercise , you can see that you can just type function name to execute the calculation especially for repetitive tasks. Type of functionsThe type of functions includes such as:
Anonymous FunctionsAnonymous functions allow you to define a function without creating a program file, as long as the function consists of a single statement. A common application of anonymous functions is to define a mathematical expression without creating a separate files. Here is how the anonymous syntax looks like output = @(arguments) expression where, output = output to be returned arguments = required inputs to be passed expression = a single formula/logic It can accept multiple inputs and return one output. They can contain only a single executable statement. Here, we have an examples of converting Fahrenheit to Celsius. >> convTempF = @(Fa) (Fa-32)*(5/9); >> convTempF(88) ans = 31.1111 >> convTempF(60) ans = 15.5556 Another example here is using anonymous function to convert minute to seconds (NOTE: 1 minute is equal to 60 seconds) >> convert_min_to_s = @(t) t*60; >> convert_min_to_s(4) ans = 240 Local functionsSometimes in mathematics, you might be encountering an issue where you might find a use case where function that are better to be calculated within its own function. The application for this local functions is in a complex function, it would be easier to be broken down to smaller piece of functions and we are certain that the functions are going to be used in same functions and not at other functions. Examples of local functionsTo illustrate an examples, we will create a function statistik which will take in a series of number and return an output of basic function of statistic such as max, min, average and standard deviation. We will give it just a sting of random numbers and it will produce all the usual statistic results. First of all, we need to create a function named statistik , follow the instruction here at Create Functions in Separate Files function [max,min,ave,stdev] = statistik(v) % this is the main function and can call to other local functions % The function where it takes arguments of series and it will calculate the basic statistic info % min function selects the smallest number in the series % max function selects the largest number in the series % ave function calculate the average of the series % stdev function calculate the standard deviations max = maxf(v); min = minf(v); ave = avef(v); stdev = stdevf(v); end %end of function statistik function a=maxf(v) %Sub function selects the largest number in the series a = max(v); end %end of function maxf function b= minf(v) %Sub function selects the smallest number in the series b = min(v); end %end of function minf function c = avef(v) %Sub function to calculate the average of the series c = mean(v); end %end of function avef function d = stdevf(v) %Sub function to calculate the std dev of the series d = std(v); end %end of function stdevf After creating function statistik in a separate file, we generate a random set of number inside the Command Window using randi function >> V = randi(50,1,10) V = 25 29 12 23 49 28 27 12 25 32 We call the function statistik as followed inside the Command Window: maximum = 49 minimum = 12 average = 26.2000 stdeviation = 10.4435 Although you cannot call a local function from the command line or from functions in other files, you can access its help using the help function. >> help statistik>avef Sub function to calculate the average of the series Nested FunctionNested functions are functions that are nested entirely inside the main functions. Requirements of nested functions(a) To nest any function in a program file, all functions in that file must use an end statement. Examples of nested functionsWe have a hypothetical situations where we need to estimate the weight of metal ingots which are in cylindrical shape. To start off, before we start to know the volume of ingot, we first calculate the surface area of the cylinder base which is circle. We can use the area of circle to calculate the volume of cylinder Lastly, we use the volume and density to calculate the weight In MATLAB, we formulate the formula such as these. Note: function[]=ingot_calc() %This function is to calculate the price of an cylindrical ingot r = 3 ; % radius of base circle h = 10; % height of ingot d = 4.5;% density of the metal ar = circle_area; vo = volume; we = weight; function a = circle_area %calculate area of circle for the radius a=pi*r*r; at=['Area of circle is ',num2str(a,'%8.2f') , ' cm2']; disp(at) end function v = volume %calculate volume v = ar* h; vt=['Volume of the ingot is ',num2str(v,'%8.2f') , 'cm3']; disp(vt) end function w = weight %calculate weight w = vo*d; wt=['The weight of ingot is ',num2str(w,'%8.2f'), ' g']; disp(wt) end end When we calling ingot_calc function in the command window, it should display the values >> ingot_calc Area of circle is 28.27 cm2 Volume of the ingot is 282.74cm3 The weight of ingot is 1272.35 g Inline FunctionsInline functions are currently being phased out. Anonymous functions should be used instead. Inline functions are included here for information purposes. >> convert_s_to_ms = inline('x*1000','x');
>> convert_s_to_ms(20)
ans =
20000
Function HandlesFunction handles are doubles serving as an abstract reference to the function. Handles allow an equation to be passed to another function for direct evaluation. Anonymous functions are useful for command-line evaluation or for multiple evaluations in the same m-file. The ampersat returns the handle of a function either built into Matlab or defined in an M-file. To illustrate example, we need to build a tent as shown on the picture but we need to figure out what is the amount of tarp that are needed to build the carnival tent.
Therefore, we will create two separate functions which take the radius and slant height of cone (cone) plus radius and height of cylinder (cylinder) . To refresh the your memory, formula for cone surface (remember we focus slanting area and ignore the base area) is Follow steps in Create Functions in Separate Files to start create totalsurftent function [surfcone,surfcylin] = totalsurftent(r,l,h) % The function where it takes arguments of r,l,h to calculate surface area of cylinder and cone % r is radius % l is slanting lenth of cone % h is cylinder height surfcone = sacone(r,l); surfcylin = sacylin(r,h); end function on=sacone(r,l) %Sub function to calculate face area of cylinder on = pi*r*l; end function yl= sacylin(r,h) %Sub function to calculate face area of cylinder yl = (2*pi*r*h)+(pi*r^2); end We can know the surface area by typing following commands: >> %Testing out the custom functions totalsurftent >> [areacone,areasurfcylin] = totalsurftent(3,3,3) areafcone = 28.2743 areacylin = 84.8230
Function Handles in m-filesIf you are not familiar with m-files, then skip this and come back. A function handle passes an m-file function into another function. This of course lets you have more control over what's passed there, and makes your program more general as it lets you pass any m-file (as long as it meets other requirements like having the right number of input arguments and so on). The functionality is similar to that of function pointers in C++. To pass an m-file to a function, you must first write the m-file, say something like this: function xprime = f(t,x) xprime = x; Save it as myfunc.m. To pass this to another function, say an ODE integrator, use the @ symbol as follows: >> ode45(@myfunc, [0:15], 1) One advantage of using function handles over anonymous functions is that you can evaluate more than one equation in the m-file, thus allowing you to do things like solve systems of ODEs rather than only one. Anonymous functions limit you to one equation. How to write a function that accepts a function handleFunctions can accept function handles. To do this define them as variables in your header, and then call the handles as if they were functions: % myadd adds two variables together function result = myfunc(func, a, b); result = func(a, b); [in a separate m-file] function sum = myadd(a, b) sum = a+b; The command you send to myfunc looks like this: >> result = myfunc(@myadd, 1, 2); result = 3 References |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |