# FSETC Workshops: Introduction to Functions in MATLAB
*Functions* are a way for programmers to generalize some piece of code so that it can be reused. Functions isolate the implementation details and variables used from your main program.

<p style="color: gray; padding-top: 1cm;text-align: center;">▶️Press the spacebar to continue</p>

## Anonymous Functions
*Anonymous functions* are the simplest possible function. They can only be on one line, and therefore can only be one executable statement. The following creates an anonymous function called `func`, that takes one input called `input`. Read the full documentation [here](https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html).


```octave
func = @(input) outputStatement;
```

### Example
Let's create a function that does some computation with the $\sin$ function:


```octave
f = @(x) sin(3*x) + 15;
f(0)
```

    ans =  15


### What's the deal with the `.`?
* MATLAB defaults all operations to matrix operations
* If we want to square all the elements in a list, use the `dot` to do element-wise operations
(Visual to show the difference)


```octave
f = @(x) x.^2; %try removing the dot
f([1, 2, 5])
```

    ans =
    
        1    4   25
    


### Combining Anonymous Functions
* There are times when we might want to combine multiple anonymous functions
* The following code is equivalent to 

\begin{align}
    f(t) &= \sin(t)\\
    g(t) &= \cos(t)\\
    h(t) &= f(t)g(t) \\
    &= \sin(t)\cos(t)
\end{align}


```octave
f = @(t) sin(t);
g = @(t) cos(t);
h = @(t) f(t) * g(t);   %Note that you need to call the function inside the new function.
```

## Regular Functions
* The following is the MATLAB syntax for defining a function. You can see the full documentation [here](https://www.mathworks.com/help/matlab/ref/function.html)
* Variables within a function are limited to the scope of the function
* You can pass in one function to another function

```octave
function [output] = functionName(input)
    output = %set function output
end
```

### Example: Addition
Let's define a very simple function that adds two input arguments. The function will be called `add`. The function will take two input arguments, `a` and `b`, and will return the result, `c`. Arguments are passed by position.


```octave
function [c] = add(a, b)
    c = a + b;
end
add(1, 2)
```

    ans =  3


### Example: Summation
Let's create a function that will sum all of the elements of a vector. The function is:
$$
\sum_{i=1}^N x_i
$$

where $N$ is the number of elements and $x_i$ is the $i$th element of the vector $x$.


```octave
function [total] = mySum(items)
    total = 0; % Initialize the summation
    for i = 1:length(items)
        total = total + items(i); % get the ith item; add to the total
    end
end
mySum([0, 1, 2, 3])
```

    ans =  6


### Multiple Return Values
* Functions can return more than one piece of data
* The variable name used when called doesn't matter


```octave
function [total, mean] = stats(values)
    total = sum(values);
    mean = total/length(values);
end
[out1, out2] = stats([0, 1, 2])
```

    out1 =  3
    out2 =  1


## Your turn

Create a function, `Integrate`, that computes the definite integral with trapezoidal rule from the lower bound, `a`, to an upper bound, `b`, with a spacing, `dx`. See [here](https://en.wikipedia.org/wiki/Trapezoidal_rule) for trapezoidal rule theory.
\begin{align}
I &= \int_a^b f(x) dx \\
  &\approx \frac{1}{2} \Delta x \left[ f(a) + 2\sum_{i=1}^{n-2} f(x_i) + f(b) \right]
\end{align}

where $x_i = a + i \Delta x$, $\Delta x=\frac{b-a}{n}$, and $i=[1, 2, ..., n-2]$.


```octave
function [I] = Integrate(f, a, b, Nsegments)
    % Describe function here
    
end

% Some code verification
f = @(x) sin(x);
Integrate(f, 0, 1, 10) % our function
x = 0:0.1:1;
trapz(x, f(x))         % built-in function to compare output
```

    ans =  0.45931


## Important [Gotchas](https://en.wikipedia.org/wiki/Gotcha_(programming))

* MATLAB functions should be in a separate file and the function name should match the name of the file.
    * [Local functions](https://www.mathworks.com/help/matlab/matlab_prog/local-functions.html) (only available within the current script) can be added to the bottom of script files; no other code can follow it.
* You can't directly run a MATLAB function, because they require inputs.
    * Always call your function from another file or the command window.
* Function names cannot have paretheses, spaces, etc. They follow the same rules as variable names.

## More Notebooks

* [Basics](Basics.ipynb)
* [Functions](Functions.ipynb)
* [Control Flow](Control%20Flow.ipynb)
* [Matrix Indexing](Matrix%20Indexing.ipynb)
* [Plotting](Plotting.ipynb)
* [Printing](Printing.ipynb)
* [Building Matricies](Building%20Matricies.ipynb)

fde199505233776085a6e4c7360e9bea2c0a8538
ipynb
Jupyter Notebook
Functions.ipynb
BrianChevalier/MATLAB101
7a8d7ced44c296fe3ae4f90944d96ea14bf453a6
MIT
2022-03-06T03:42:13.000Z
2022-03-06T03:42:13.000Z
Functions.ipynb
BrianChevalier/MATLAB101
7a8d7ced44c296fe3ae4f90944d96ea14bf453a6
MIT
Functions.ipynb
BrianChevalier/MATLAB101
7a8d7ced44c296fe3ae4f90944d96ea14bf453a6
MIT
Qwen/Qwen-72B
1. YES
2. YES