# Matlab function

## Introduction:

Functions in MATLAB are composed with code that link one variable with another, and yielded output is connected precisely to one specific information that shapes a significant piece of any software. In MATLAB environment, they are put away in a specific document like content records, and so forth They can acknowledge more than one information contention and can likewise return more than one yield contention. They work on the characterized factors in their predefined workspace, known as the nearby workspace.

## MATLAB’s function

Group of statements is called a function if they together perform a operation. Functions in MATLAB, are defined in separate named files. Function’s name and name of the file should be defined same.

Functions perform various operations on variables in the prescribed workspace, which is often referred as **local workspace**, you access these variables at the MATLAB command prompt or we call it as **base workspace**.

Many arguments as input is accepted by a function and it returns one or more output arguments at a time.

## Syntax of a MATLAB’s function statement is –

```
function [output1,output2, ..., outputN]
= myfun(input1,input2,input3, ..., inputN)
```

## Create Functions in Files

To reuse sequences of commands which is supported by both scripts and functions, allows us to store them in files. Scripts are small piece of code they store commands and allows you to type them at the MATLAB’s command line. Primarily functions provide more flexibility, because it can return output values based on input values we pass. For example, `factof() function`

calculates the factorial and returns the output (`w`

) of a integer number (`n1`

).

```
function w = factof(n1)
w = prod(1:n1);
end
```

We can now call our function from the command line, using function call. Let’s take an example, by calculating the factorial of number 3.

```
X1 = 3;
Y1 = fact(3)
Y1 =6
```

## Some rules for saving the function and rational function’s name:

- The function name should begin with alphabets and can contain characters, number, underscores these all are considered as valid function name.
- To save the function, we need to save in the function file that contains function variables and definitions, and the function name must match the file name which contains that function.
- In functions which contains function definitions and commands, we can also save the function here. Functions declared in the file should be defined at the finish line of the file, and the script name in the file must be not equal to the name of the function.
- To indicate the termination of function, a keyword should be used named “end”.
- In a file, when a function defined has a nested function in it or say it as local function, it is required to be inside the script file.

## Types of MATLAB’s Functions

## 1. Anonymous Function

When a function that is not contained by any file, but it is connected through function_handle with a variable, those type of function is called Anonymous function.

This function is defined in a single statement function, which has any no. of input or output arguments.

The syntax is as follows:

```
[email protected](argslist)expressions
funp =
function_handle with value:
@(argslist)expressions
```

By creating a script file and typing the following code we can understand the above said concept easily–

```
power = @(x, n) x.^n;
res1 = power(5, 3)
res2 = power(59, 0.5)
res3 = power(20, -20)
res4 = power (3.5, 1.5)
```

```
res1 =
125
res2 =
7.6811
res3 =
9.5367e-27
res4 =
6.568
```

## 2. Local Functions

Any function document contains an essential function that shows up in the primary line of the code. They are noticeable to functions in different documents and can be brought in the order line. Different functions that are available in the document are called neighborhood functions. From the command line it is not possible to be called and are visible to a parent or fundamental functions and functions written in a similar document. They are otherwise called sub-functions. They are identical to subroutines as utilized in another programming language. They can likewise be written in script records as long as they show up after the last line of the content code.

**Example:**

We are creating a function file my*quadratic.m* and code it -

```
function [p1,p2] = myquadratic(a1,b1,c1)
d1 = disc(a1,b1,c1);
p1 = (-b1 + d1) / (2*a1);
p2 = (-b1 - d1) / (2*a1);
end % end of quadratic
function dis1 = disc(a1,b1,c1)
%function calculates the discriminant
dis1 = sqrt(b1^2 - 4*a1*c1);
end % end of sub-function
```

We can now call the function from command line as follows -

`myquadratic(2,3,-3)`

The above statement is executed and returns the result as follows -

`ans = 0.6346`

## 3. Nested Functions

When functions are defined within a parent function or function then they are called as nested functions. Now this function can modify the defined variables of the parent function. They can be fetched from the workspace easily and they are defined in a scope of parent function only.

There are few rules or needs that every nested function should be satisfied:

- The end statement is not required by all functions. However, end statement should be written for each function if we want to nest any function.
- Nested functions are not defined inside any control statements like if-else, while, if-else..end, switch case, etc.
- Nested functions can be called in two ways i.e
- By calling its name
- And through the function handle of that function.

**Syntax**

```
function x = w(q1, q2)
...
v(q2)
function y = v(q3)
...
end
...
end
```

**Example:**

We are creating a function file my*quadratic2.m* and code it -

```
function [p1,p2] = myquadratic2(a1,b1,c1)
function disc
d1 = sqrt(b1^2 - 4*a1*c1);
end % function end
disc;
p1 = (-b1 + d1) / (2*a1);
p2 = (-b1 – d1) / (2*a1);
end % function end
```

We can now call the function from command line as follows -

`myquadratic(2,3,-3)`

The above statement is executed and returns the result as follows -

`ans = 0.6346`

## 4. Private Functions

Few functions are only visible to privileged group of functions. They are defined inside sub-functions and the keyword “private” is used to denote them. The parent folder functions can only see these private functions or the functions in the main folder which are above the private subfolder. When we want to alter the range of scope of the function they are very helpful. It is not possible to call “private functions” from the outside of the parent folder or directly from the command line.

We are Creating a subfolder “private” in our working directory. Reserve the function file my*disc.m *in it -

```
function dis = mydisc(a1,b1,c1)
%this calculates the discriminant
dis = sqrt(b1^2 - 4*a1*c1);
end % end of sub-function
```

We are creating a function myquadratic3.m in working directory and code in it as follows

This function calculates quadratic equation roots , It takes the constant term and the co-efficient of p2, p (total three arguments )and it returns the roots.

```
function [p1,p2] = quadratic3(a1,b1,c1)
D1 = disc(a1,b1,c1);
p1 = (-b1 + d1) / (2*a1);
p2 = (-b1 – d1) / (2*a1);
end % end of quadratic3
```

You can execute from command prompt by calling the above function as -

`myquadratic3(2,4,-4)`

MATLAB returns the following result -

`ans = 0.73205`

## Global Variables

The global variables can be used by one or more functions. For this, you need to pronounce the variable by using keyword “global” in every one of the functions.

Assuming you need to get that factor, pronounce the variable at the command line from the base workspace.

The global declaration should happen before the variable is really utilized in a capacity. It's anything but a decent practice to utilize capital letters for the names of global factors to recognize them from different factors.

**Example:**

A function file named myaverage.m is created and code it as follows -

```
function avg = myaverage(numbers)
global myTOTAL
avg = sum(numbers)/myTOTAL;
end
```

we are creating a script file and code it as follows -

```
global myTOTAL;
myTOTAL = 10;
n1 = [4, 5, 5, 5, 3, 9, 0, 4, 8, 2];
bv = myaverage(n1)
```

Now run the file, it will output the following result -

`bv = 43.20`

## Conclusion – MATLAB Functions

MATLAB Functions can be utilized for a few undertakings and situations. They structure a fundamental piece of any programming language. They can be gotten to internationally by utilizing worldwide factors or private capacities on the off chance that we need some data or substance to be private. They are utilized in each association for the business needs to satisfy the requests.