% Jake Bobowski
% August 17, 2017
% Created using MATLAB R2014a

% This tutorial discusses how to define functions within a MATLAB script.
% Once defined, the functions can be evaluated, differentiated, integrated,
% plotted, ...  Also, if you've taken a look at the nonlinear fitting
% tutorial, you'll have seen that model functions that are fit to the data
% need to be defined.
clearvars

% First, we use syms to define the symbolic variable x
syms x;

% The notation used to define a function is a bit strange.  The function
% parameters are listed inside @(...), then a space is left before typing
% in the form of the function.  Here's how to define f to be sin(x).
f = @(x) sin(x);

% Once defined, it's easy to evaluate the function at any value of x.
f(0)
f(pi/4)
f(pi/2)

% We can also take a symbolic derivative of x...
diff(f(x), x)

% or a symbolic integral...
int(f(x), x)

% or a definite integral
int(f(x), x, 0, pi)

% We can also input a vector of x-values and evaluate the function at each
% value of x contained in the vector.
xx = 0:0.05:2*pi;
y = f(xx)

% These data can then easily be plotted.
plot(xx, y, 'bo')
xlabel('x')
ylabel('f(x) = sin x')

% Here's another simple function: g(x) = x^2.
g = @(x) x.^2;

% Of course, we can also evaluate this function at any value of x.
g(10)

% We can also next functions.  Here's how to construct sin(x^2)...
h = @(x) f(g(x));

% and here's (sin x)^2.
l = @(x) g(f(x));

% Can now get MATLAB to apply the chain rule for us.
diff(h(x), x)
diff(l(x), x)

% Everything above was for a function of a single variable.  You can, of
% course, have a function of any number of variables.  Here's a simple 
% function of two variables:
syms y;
k = @(x, y) x.^2 + y.^2;
k(1, 2)
