Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

MATLAB Programming/Portable Functions

From Wikibooks, open books for an open world
<MATLAB Programming
Thelatest reviewed version waschecked on11 December 2024. There aretemplate/file changes awaiting review.

[MATLAB Programming\|/MATLAB Programming]m]

Chapter 1: MATLAB ._.

Introductions .
Fundamentals of MATLAB
MATLAB Workspace
MATLAB Variables
*.mat files

Chapter 2: MATLAB Concepts

MATLAB operator
Data File I/O

Chapter 3: Variable Manipulation

Numbers and Booleans
Strings
Portable Functions
Complex Numbers

Chapter 4: Vector and matrices

Vector and Matrices
Special Matrices
Operation on Vectors
Operation on Matrices
Sparse Matrices

Chapter 5: Array

Arrays
Introduction to array operations
Vectors and Basic Vector Operations
Mathematics with Vectors and Matrices
Struct Arrays
Cell Arrays

Chapter 6: Graphical Plotting

Basic Graphics Commands
Plot
Polar Plot
Semilogx or Semilogy
Loglog
Bode Plot
Nichols Plot
Nyquist Plot

Chapter 7: M File Programming

Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
Debugging M Files

Chapter 8: Advanced Topics

Numerical Manipulation
Advanced File I/O
Object Oriented Programming
Applications and Examples
Toolboxes and Extensions

Chapter 9: Bonus chapters

MATLAB Benefits and Caveats
Alternatives to MATLAB
[MATLAB_Programming/GNU_Octave|What is Octave= (8) hsrmonic functions]
Octave/MATLAB differences

edit this box

Functions in MATLAB

[edit |edit source]

A 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 namedmyfunc that accepts inputsx1,...,xM and returns outputsy1,...,yN .
This declaration statement must be the first executable line of the function. Valid function names begin with an alphabetic character, and can contain letters, numbers, or underscores.

Create Functions in Separate Files

[edit |edit source]
Screenshot of MATLAB on how to select "Function"
Screenshot of MATLAB on how to select "Function"

To 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 hereoutputArg1=inputArg1;outputArg2=inputArg2;end

Declare a function

[edit |edit source]

To demonstrate a function usefulness, we are going to take a hypothetical situations ,
Recently, in your class there are some exchange students from America whom are consistently complaining the weather is hot outside, when they check on their weather app, they exclaimed the weather is100 degrees outside. But as to the people who never uses the imperial units before, you might wonder, what is the temperature outside right now ?

So, to solve the question, it might be a good time to create a custom functions to convert from Fahrenheit to Celsius .
First of all, we must know the conversion formula from Fahrenheit to Celsius which is given as:Co=(Fo32)59{\displaystyle C^{o}=(F^{o}-32)*{\frac {5}{9}}}

At "Home" tab, click on "New" ---> "Functions"

function[Ce]=convertTemp(Fa)% Convert from Fahrenheit to CelciusCe=(Fa-32)*(5/9);end

Click on save button to save the functions asconvertTemp.m file
Note: The filename MUST be same as function name or else it won't work !

Later, on theCurrent Folder Panel, select the directory where you save the function files just now.

Calling a function

[edit |edit source]

To call the newly created function, do the following:On theCommand Window Panel, type this command as shown

>>convertTemp(100)ans=37.7778

Hence, the weather outside is almost38 Celsius degrees.

Benefits of functions

[edit |edit source]

Why 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.
Just imagine for example above, it will be a real time saver to just type function convertTemp instead of manually typing formula each tims.

Type of functions

[edit |edit source]

The type of functions includes such as:

  • Anonymous Functions
  • Local Functions
  • Nested Functions
  • Private Functions
  • Inline function (Phased out in future version)

Anonymous Functions

[edit |edit source]

Anonymous 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 returnedarguments = required inputs to be passedexpression = 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 functions

[edit |edit source]

Sometimes 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.
Rather than running separate functions to get one output, you just need to run just one function to get the multiple output. This is where local functions comes in.
To clarify further, in a function file, thefirst function in the file is called the main or parent function. Additional functions within the file are calledlocal functions, and they can occur in any order after the main function. Local functions are only visible to other functions in the same file. These are equivalent to subroutines in other programming languages, and are sometimes called sub-functions.

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 functions

[edit |edit source]

To illustrate an examples, we will create a functionstatistik 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 atCreate 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 deviationsmax=maxf(v);min=minf(v);ave=avef(v);stdev=stdevf(v);end%end of function statistikfunctiona=maxf(v)%Sub function selects the largest number in the seriesa=max(v);end%end of function maxffunctionb=minf(v)%Sub function selects the smallest number in the seriesb=min(v);end%end of function minffunctionc=avef(v)%Sub function to calculate the average of the seriesc=mean(v);end%end of function aveffunctiond=stdevf(v)%Sub function to calculate the std dev of the seriesd=std(v);end%end of function stdevf

After creating functionstatistik in a separate file, we generate a random set of number inside the Command Window usingrandi function

>>V=randi(50,1,10)V=25291223492827122532

We call the function statistik as followed inside the Command Window:
[maximum,minimum,average,stdeviation]=statistik(V)

maximum=49minimum=12average=26.2000stdeviation=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.
Specify names of both the file and the local function, separating them with a > character.

>>helpstatistik>avefSubfunctiontocalculatetheaverageoftheseries

Nested Function

[edit |edit source]

Nested functions are functions that are nested entirely inside the main functions.
The primary difference between nested functions and local functions is that nested functions can use variables defined in parent functions without explicitly passing those variables as arguments.

Requirements of nested functions

[edit |edit source]

(a) To nest any function in a program file, all functions in that file must use an end statement.
(b) A nested function can't be defined inside any of the program control statements, such as if/elseif/else, switch/case, for, while, or try/catch.
(c) A nested function either directly by function name , or using a function handle that you created using the @ operator (refer to anonymous function).
(d) All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace.

Examples of nested functions

[edit |edit source]
Cylindrical metal ingots

We have a hypothetical situations where we need to estimate the weight of metal ingots which are in cylindrical shape.
First, before we started on figuring out the metal ingots weight, we need to break down the problems into smaller piece.
To figure out the weight of the metal, we need to figure out the density and before figuring out density we need to figure out volume of the metal.

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.
Area of circles is defined asA=Πr2{\displaystyle A=\Pi r^{2}}
,r is radius of base circle

We can use the area of circle to calculate the volume of cylinder
V=Ah{\displaystyle V=A*h}
,h is height of cylinder.V=(Πr2)h{\displaystyle V=(\Pi r^{2})h}

Lastly, we use the volume and density to calculate the weight
W=VD{\displaystyle W=V*D}
where D is density.

How to increase indent

In MATLAB, we formulate the formula such as these.
Note: For the nested functions beside main functions, we need to indent the functions .Editor -> Indent.

Note:

function[]=ingot_calc()%This function is to calculate the price of an cylindrical ingotr=3;% radius of base circleh=10;% height of ingotd=4.5;% density of the metalar=circle_area;vo=volume;we=weight;functiona=circle_area%calculate area of circle for the radiusa=pi*r*r;at=['Area of circle is ',num2str(a,'%8.2f'),' cm2'];disp(at)endfunctionv=volume%calculate volumev=ar*h;vt=['Volume of the ingot is ',num2str(v,'%8.2f'),'cm3'];disp(vt)endfunctionw=weight%calculate weightw=vo*d;wt=['The weight of ingot is ',num2str(w,'%8.2f'),' g'];disp(wt)endend

When we callingingot_calc function in the command window, it should display the values

>>ingot_calcAreaofcircleis28.27cm2Volumeoftheingotis282.74cm3Theweightofingotis1272.35g

Inline Functions

[edit |edit source]

Inline 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 Handles

[edit |edit source]
Outdoor carnival tent

Function 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Πrl{\displaystyle \Pi rl}
and cylinder surface (remember that one side of circle of cylinder is not calculated) is2Πrh+Πr2{\displaystyle 2\Pi rh+\Pi r^{2}}
, where ther is the shared radius of cylinder and cone,l is the length of slanting height of cone and finallyh is height of cylinder.

Follow steps inCreate Functions in Separate Files to start createtotalsurftent

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 heightsurfcone=sacone(r,l);surfcylin=sacylin(r,h);endfunctionon=sacone(r,l)%Sub function to calculate face area of cylinderon=pi*r*l;endfunctionyl=sacylin(r,h)%Sub function to calculate face area of cylinderyl=(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.2743areacylin=84.8230


Function Handles in m-files

[edit |edit source]

If you are not familiar with m-files, then skip this and come back.

A function handle passes anm-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 passany 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 solvesystems of ODEs rather than only one. Anonymous functions limit you to one equation.

How to write a function that accepts a function handle

[edit |edit source]

Functions 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 togetherfunction 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

[edit |edit source]

[1][2][3]

  1. https://blogs.mathworks.com/loren/2008/01/16/nested-functions-and-variable-scope/
  2. https://web.archive.org/web/20220727140850/https://www.geeksforgeeks.org/functions-in-matlab/
  3. https://web.archive.org/web/20220730143213/https://www.educba.com/matlab-functions/
Retrieved from "https://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Portable_Functions&oldid=4603747"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp