Write matlab function

Write matlab function DEFAULT

Introduction: Creating a Function in MATLAB

MATLAB is a tool that engineers and other professionals can use to quickly and efficiently analyze data, make calculations, and display information. One of the many ways that the user can interact with MATLAB is through the use of functions. Functions receive specific information, known as inputs, and use the inputs to calculate other information to display, known as outputs. This instructable will detail the process of creating a function and will guide the user through creating a function of their own.

To complete this instructable, you will need:

1. A computer with access to MATLAB

2. 5-10 minutes

Step 1: Open MATLAB

First, open the start menu by pressing the Windows button in the bottom left corner of the screen, or by pressing the Windows key on your keyboard. Then, type MATLAB into the search bar and select "MATLAB R2013a." Note that the exact name of the program may vary slightly if your version of MATLAB is older. You should still see the same symbol as shown in the image even if your version is older, so you should use this to find the right program.

Step 2: Open Script Window

When MATLAB opens, the user is taken to MATLAB's primary window, also known as the Command Window.  In order to create a function, however, the user must open the Script Window.  Select the highlighted button to open the Script Window. Scripts are saveable sequences of commands that can be run all at once. A function is a special kind of script that can take different inputs each time it is run.  Note that in older versions of MATLAB, the highlighted button will not appear, and the user must select File > New > Script in order to open the Script Window.

Step 3: The First Line

Once the Script Window opens, type "function f = make_a_square(x)" into line 1. The word "function" tells MATLAB that this script will be a function. The text between the word "function" and the = signifies the output of the function, in this case being "f". The text inside of the parentheses signifies the input, in this case being "x." Finally, the text directly to the left of the parentheses is the name of the function, which in this case is called "make_a_square."

Step 4: Finishing the Function

Once the first line of the function is entered, complete the code by entering "f=x^2;" on line 2 and "end" on line 3. The second line tells MATLAB to take the input, square it, and set the new number as the output. The semicolon ending the line stops MATLAB from outputting that line later. Were the semicolon not used, the output would display twice when we used the function later on. Line 3 tells MATLAB that the function has concluded.

Step 5: Saving the Function

Once your function is complete, save the function using the save button. The default name of the save file will be the same as the name of the function. Make sure that you do not change this. Changing the name of the save so that it is not the same as the name on line 1 can cause the function to not work properly.  Note that, as in Step 2, older versions of MATLAB will not have the highlighted button, so saving must also be accomplished through the File menu.

Step 6: Running the Function

Return to the Command Window. Enter "make_a_square(3)" and hit Enter on your keyboard to test your function. Your code should square the number 3, outputting 9. If the code does not do this, check to make sure that you spelled the function correctly in the Command Window. If this does not solve the problem, reopen your function in the Script Window and ensure that there are no errors. Once you code is outputting correctly, you will have successfully created your first MATLAB function!

Be the First to Share

Did you make this project? Share it with us!


  • Retro Tech Challenge

    Retro Tech Challenge
  • 3D Printed Student Design Challenge

    3D Printed Student Design Challenge
  • Robots Contest

    Robots Contest
Sours: https://www.instructables.com/Creating-a-Function-in-MATLAB/

Select a Web Site

Add Functions to Scripts

Starting in R2016b, MATLAB® scripts, including live scripts, can contain code to define functions. These functions are called local functions. Local functions are useful if you want to reuse code within a script. By adding local functions, you can avoid creating and managing separate function files. They are also useful for experimenting with functions, which can be added, modified, and deleted easily as needed.

Create a Script with Local Functions

To create a script or live script with local functions, go to the Home tab and select New Script or New Live Script. Then, add code to the file. Add all local functions at end of the file, after the script code. Include at least one line of script code before the local functions. Each local function must begin with its own function definition statement and end with the keyword. The functions can appear in any order.

For example, create a script called .

In the file, include two local functions, and . The script declares an array, determines the length of the array, and then uses the local functions and to calculate the average and median of the array.

x = 1:10; n = length(x); avg = mymean(x,n); med = mymedian(x,n); function a = mymean(v,n) % MYMEAN Local function that calculates mean of array. a = sum(v)/n; endfunction m = mymedian(v,n) % MYMEDIAN Local function that calculates median of array. w = sort(v); if rem(n,2) == 1 m = w((n + 1)/2); else m = (w(n/2) + w(n/2 + 1))/2; endend

When you add local functions to a live script, MATLAB automatically adds a section break before the first local function definition and removes all section breaks after it. This is because the Live Editor does not support individual sections within local functions.

Run Scripts with Local Functions

To run a script or live script that includes local functions, in the Editor or Live Editor tab, click the Run button. You also can type the saved script name in the Command Window.

To run an individual section inside a script or live script, place the cursor inside the section and use the Run Section button (requires R2017b or later for files). In live scripts or functions ( files), you only can run sections that are before the local function definitions.

Restrictions for Local Functions and Variables

Local functions are only visible within the file where they are defined. They are not visible to functions in other files, and cannot be called from the Command Window.

Local functions in the current file have precedence over functions in other files. That is, when you call a function within a script, MATLAB checks whether the function is a local function before looking for the function in other locations. This allows you to create an alternate version of a particular function while retaining the original in another file.

Scripts create and access variables in the base workspace. Local functions, like all other functions, have their own workspaces that are separate from the base workspace. Local functions cannot access variables in the workspace of other functions or in the base workspace, unless you pass them as arguments.

Access Help for Local Functions

Although you cannot call a local function from the command line or from functions in other files, you can access its help using the command. Specify the names of both the script and the local function, separating them with a character.

For example:

mymean Local function that calculates mean of array.

Related Topics

Sours: https://www.mathworks.com/help/matlab/matlab_prog/local-functions-in-scripts.html
  1. Dewey pest control
  2. Thunderbolt™ 3
  3. Kirby 64 corruptions
  4. Lg stylus tmobile
  5. Walmart computer desk

How to create a function in MATLAB ?

A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functionswhich are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions.


function output_params = function_name(iput_params)

       % Statements


  • The function starts with the keyword function.
  • Returning variables of the function are defined in output_params
  • function_name specifies the name of the function
  • input_params are input arguments to the function

Below are some examples that depict how to use functions in MATLAB:

Example 1: Function with one output

The function calculates the mean of the input vector






Output :


mean = 6.7800


Example 2: Function with multiple outputs


The function calculates both nCr and nPr of inputs n and r.







Output :


p = 6 c = 12


Example 3: Multiple functions in a file


  • stat2() function calculates the standard deviation of the input vector.
  • stat1() calculates the mean of the input vector.






Output :

n = 5 ans = 3.2975

Example 4: Function with no input_params

In this program, we will create the sin_plot() function that plots the sin() function





Output :



Sours: https://www.geeksforgeeks.org/how-to-create-a-function-in-matlab/


Main Content



declares a function named that accepts inputs and returns outputs . 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.

You can save your function:

  • In a function file which contains only function definitions. The name of the file must match the name of the first function in the file.

  • In a script file which contains commands and function definitions. Functions must be at the end of the file. Script files cannot have the same name as a function in the file. Functions are supported in scripts in R2016b or later.

Files can include multiple local functions or nested functions. For readability, use the keyword to indicate the end of each function in a file. The keyword is required when:

  • Any function in the file contains a nested function.

  • The function is a local function within a function file, and any local function in the file uses the keyword.

  • The function is a local function within a script file.


collapse all

Function with One Output

Define a function in a file named that accepts an input vector, calculates the average of the values, and returns a single result.

function ave = average(x) ave = sum(x(:))/numel(x); end

Call the function from the command line.

z = 1:99; ave = average(z)

Function with Multiple Outputs

Define a function in a file named that returns the mean and standard deviation of an input vector.

function [m,s] = stat(x) n = length(x); m = sum(x)/n; s = sqrt(sum((x-m).^2/n)); end

Call the function from the command line.

values = [12.7, 45.4, 98.9, 26.6, 53.1]; [ave,stdev] = stat(values)
ave = 47.3400 stdev = 29.4124

Function in a Script File

Define a script in a file named that computes the value of the integrand at $2\pi/3$ and computes the area under the curve from 0 to $\pi$. Include a local function that defines the integrand, $y = \sin(x)^3$.

Note: Including functions in scripts requires MATLAB® R2016b or later.

% Compute the value of the integrand at 2*pi/3. x = 2*pi/3; y = myIntegrand(x) % Compute the area under the curve from 0 to pi. xmin = 0; xmax = pi; f = @myIntegrand; a = integral(f,xmin,xmax) function y = myIntegrand(x) y = sin(x).^3; end

Multiple Functions in a Function File

Define two functions in a file named , where the first function calls the second.

function [m,s] = stat2(x) n = length(x); m = avg(x,n); s = sqrt(sum((x-m).^2/n)); endfunction m = avg(x,n) m = sum(x)/n; end

Function is a local function. Local functions are only available to other functions within the same file.

Call function from the command line.

values = [12.7, 45.4, 98.9, 26.6, 53.1]; [ave,stdev] = stat2(values)
ave = 47.3400 stdev = 29.4124

Function with Argument Validation

Define a function that restricts input to a numeric vector that contains no or elements. This function uses the keyword, which is valid for MATLAB® versions R2019b and later.

function [m,s] = stat3(x) arguments x (1,:) {mustBeNumeric, mustBeFinite}end n = length(x); m = avg(x,n); s = sqrt(sum((x-m).^2/n)); endfunction m = avg(x,n) m = sum(x)/n; end

In the code block, indicates that must be a vector. The validation functions, , restrict the elements in to numeric values that are not or . For more information, see Function Argument Validation.

Calling the function with a vector that contains an element that is violates the input argument declaration. This violation results in an error being thrown by the validation function.

values = [12.7, 45.4, 98.9, NaN, 53.1]; [ave,stdev] = stat3(values)
Invalid input argument at position 1. Value must be finite.

Introduced before R2006a

You have a modified version of this example. Do you want to open this example with your edits?

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

Select web site

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Contact your local office

Sours: https://www.mathworks.com/help/matlab/ref/function.html

Function write matlab


Teaching: 45 min
Exercises: 20 min

  • How can I teach MATLAB how to do new things?

  • Compare and contrast MATLAB function files with MATLAB scripts.

  • Define a function that takes arguments.

  • Test a function.

  • Recognize why we should divide programs into small, single-purpose functions.

If we only had one data set to analyze, it would probably be faster to load the file into a spreadsheet and use that to plot some simple statistics. But we have twelve files to check, and may have more in future. In this lesson, we’ll learn how to write a function so that we can repeat several operations with a single command.

Let’s start by defining a function that converts temperatures from Fahrenheit to Kelvin:

A MATLAB function must be saved in a text file with a extension. The name of that file must be the same as the function defined inside it. The name must start with a letter and cannot contain spaces. So, you will need to save the above code in a file called . Remember to save your m-files in the current directory.

The first line of our function is called the function definition, and it declares that we’re writing a function named , that has a single input parameter,, and a single output parameter, . Anything following the function definition line is called the body of the function. The keyword marks the end of the function body, and the function won’t know about any code after .


A function can have multiple input and output parameters if required, but isn’t required to have any of either. The general form of a function is shown in the pseudo-code below:

Just as we saw with scripts, functions must be visible to MATLAB, i.e., a file containing a function has to be placed in a directory that MATLAB knows about. The most convenient of those directories is the current working directory.

GNU Octave

In common with MATLAB, Octave searches the current working directory and the path for functions called from the command line.

We can call our function from the command line like any other MATLAB function:

When we pass a value, like , to the function, the value is assigned to the variable so that it can be used inside the function. If we want to return a value from the function, we must assign that value to a variable named —in the first line of our function, we promised that the output of our function would be named .

Outside of the function, the variables and aren’t visible; they are only used by the function body to refer to the input and output values.

This is one of the major differences between scripts and functions: a script can be thought of as automating the command line, with full access to all variables in the base workspace, whereas a function can only read and write variables from the calling workspace if they are passed as arguments — i.e. a function has its own separate workspace.

Now that we’ve seen how to convert Fahrenheit to Kelvin, it’s easy to convert Kelvin to Celsius.

Again, we can call this function like any other:

What about converting Fahrenheit to Celsius? We could write out the formula, but we don’t need to. Instead, we can compose the two functions we have already created:

Calling this function,

we get, as expected:

This is our first taste of how larger programs are built: we define basic operations, then combine them in ever-larger chunks to get the effect we want. Real-life functions will usually be larger than the ones shown here—typically half a dozen to a few dozen lines—but they shouldn’t ever be much longer than that, or the next person who reads it won’t be able to understand what’s going on.

Concatenating in a Function

In MATLAB, we concatenate strings by putting them into an array or using the function:

Write a function called that has two parameters, and and adds before and after :


If the variable refers to a string, then is the string’s first character and is its last. Write a function called that returns a string made up of just the first and last characters of its input:


Variables Inside and Outside Functions

Consider our function from earlier in the episode:

What does the following code display when run — and why?


is 0 because the function has no knowledge of the variable which exists outside of the function.

Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let’s write a function to center a dataset around a particular value:

We could test this on our actual data, but since we don’t know what the values ought to be, it will be hard to tell if the result was correct, Instead, let’s create a matrix of 0’s, and then center that around 3:

That looks right, so let’s try out function on our real data:

It’s hard to tell from the default output whether the result is correct–this is often the case when working with fairly large arrays–but, there are a few simple tests that will reassure us.

Let’s calculate some simple statistics:

And let’s do the same after applying our function to the data:

That seems almost right: the original mean was about 6.1, so the lower bound from zero is now about -6.1. The mean of the centered data isn’t quite zero–we’ll explore why not in the challenges–but it’s pretty close. We can even go further and check that the standard deviation hasn’t changed:

The difference is very small. It’s still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some documentation for our function to remind ourselves later what it’s for and how to use it.

Comment lines immediately below the function definition line are called “help text”. Typing brings up the help text for that function:

Testing a Function

  1. Write a function called that takes an array as input and returns an array of the same shape with its values scaled to lie in the range 0.0 to 1.0. (If L and H are the lowest and highest values in the input array, respectively, then the function should map a value v to (v - L)/(H - L).) Be sure to give the function a comment block explaining its use.

  2. Run to see how to use to generate regularly-spaced values. Use arrays like this to test your function.


Convert a script into a function

Write a function called which plots the three summary graphs (max, min, std) for a given inflammation data file.

The function should operate on a single data file, and should have two parameters: and . When called, the function should create the three graphs produced in the previous lesson. Whether they are displayed or saved to the directory should be controlled by the value of i.e. should display the corresponding graphs for the first data set; should save the figures for the second dataset to the directory.

You should mostly be reusing code from the script.

Be sure to give your function help text.


Automate the analysis for all files

Modify the script so that as it loops over the data files, it calls the function for each file in turn. Your script should save the image files to the ‘results’ directory rather than displaying the figures in the MATLAB GUI.


We have now solved our original problem: we can analyze any number of data files with a single command. More importantly, we have met two of the most important ideas in programming:

  1. Use arrays to store related values, and loops to repeat operations on them.

  2. Use functions to make code easier to re-use and easier to understand.

Key Points

  • Break programs up into short, single-purpose functions with meaningful names.

  • Define functions using the keyword.

Sours: https://swcarpentry.github.io/matlab-novice-inflammation/07-func/index.html
MATLAB Scripting - 5 - How To Write Function In M Script

Function Creation

Create Functions in Files

Store multiple commands in a program file that can accept inputs and return output.

Types of Functions

There are several types of functions available with MATLAB®, including local functions, nested functions, private functions, and anonymous functions.

Function Precedence Order

To determine which function to call when multiple functions in the current scope have the same name, MATLAB uses function precedence order.

Add Help for Your Program

Help text appears in the Command Window when you use the function. Create help text for your program by inserting comments at the beginning.

Indexing into Function Call Results

This topic describes how to dot index into temporary variables created by function calls.

Configure the Run Button for Functions

Run functions that require some initial setup from the Editor by configuring the Run button.

Sours: https://www.mathworks.com/help/matlab/function-basics.html

Similar news:

Select a Web Site

Create Functions in Files

Both scripts and functions allow you to reuse sequences of commands by storing them in program files. Scripts are the simplest type of program, since they store commands exactly as you would type them at the command line. Functions provide more flexibility, primarily because you can pass input values and return output values. For example, this function named computes the factorial of a number () and returns the result ().

function f = fact(n) f = prod(1:n); end

This type of function must be defined within a file, not at the command line. Often, you store a function in its own file. In that case, the best practice is to use the same name for the function and the file (in this example, ), since MATLAB® associates the program with the file name. Save the file either in the current folder or in a folder on the MATLAB search path.

You can call the function from the command line, using the same syntax rules that apply to functions installed with MATLAB. For instances, calculate the factorial of 5.

Starting in R2016b, another option for storing functions is to include them at the end of a script file. For instance, create a file named with a few commands and two functions, and . The script calculates the permutation of (3,2).

x = 3; y = 2; z = perm(x,y) function p = perm(n,r) p = fact(n)/fact(n-r); endfunction f = fact(n) f = prod(1:n); end

Call the script from the command line.

Syntax for Function Definition

The first line of every function is the definition statement, which includes the following elements.

keyword (required)

Use lowercase characters for the keyword.

Output arguments (optional)

If your function returns one output, you can specify the output name after the keyword.

function myOutput = myFunction(x)

If your function returns more than one output, enclose the output names in square brackets.

function [one,two,three] = myFunction(x)

If there is no output, you can omit it.

Or you can use empty square brackets.

function [] = myFunction(x)

Function name (required)

Valid function names follow the same rules as variable names. They must start with a letter, and can contain letters, digits, or underscores.


To avoid confusion, use the same name for both the function file and the first function within the file. MATLAB associates your program with the file name, not the function name. Script files cannot have the same name as a function in the file.

Input arguments (optional)

If your function accepts any inputs, enclose their names in parentheses after the function name. Separate inputs with commas.

function y = myFunction(one,two,three)

If there are no inputs, you can omit the parentheses.


When you define a function with multiple input or output arguments, list any required arguments first. This ordering allows you to call your function without specifying optional arguments.

Contents of Functions and Files

The body of a function can include valid MATLAB expressions, control flow statements, comments, blank lines, and nested functions. Any variables that you create within a function are stored within a workspace specific to that function, which is separate from the base workspace.

Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.

End Statements

Functions end with either an statement, the end of the file, or the definition line for a local function, whichever comes first. The statement is required if:

  • Any function in the file contains a nested function (a function completely contained within its parent).

  • The function is a local function within a function file, and any local function in the file uses the keyword.

  • The function is a local function within a script file.

Although it is sometimes optional, use  for better code readability.

See Also

Related Topics

Sours: https://www.mathworks.com/help/matlab/matlab_prog/create-functions-in-files.html

10651 10652 10653 10654 10655