\documentclass{beamer}
\usepackage{verbatim}
\usepackage{amsmath, array, amsthm, amsmath,mathrsfs}
% \usepackage{ulem}
\newcommand{\R}{\mathbb{R}}
\usepackage[numbered,framed]{mcode}

% \usepackage{beamerthemesplit} // Activate for custom appearance

\title{The Abridged Matlab Crash Course}
\author{Adam Attarian}
\date{\today}

\begin{document}

\frame{\titlepage}

%\section[Outline]{}
%\frame{\tableofcontents}

%\section{Introduction}
%\subsection{Overview of the Beamer Class}

\begin{frame}[fragile]{First thing is first\dots}
\begin{itemize} 
\item For help on any command, use the \verb+help+ command. This is the most important command there is. For more info, type \verb+doc command+. This is how we learn how to use Matlab.
\item \verb+clear+ clears all of the variables out of your workspace.
\item \verb+clc+ clears the command window.
\item Anything behind a \verb+%+ is a comment and is not executed. Comment liberally.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Entering Matrices}

MATLAB works with essentially one kind of object: a rectangular matrix with possibly complex entries. 1-by-1 matrices are scalars, and matrices with one row or column are vectors.

Matrices can be input into MATLAB several ways:
\begin{itemize}
\item Entered explicitly
\item Generated by functions or statements
\item Imported from external data.
\end{itemize}

Example: \verb+A=[1 2 3; 4 5 6; 7 8 9]+ enters a $3 \times 3$ matrix and assigns it to the variable \verb+A+, where the `;' starts a new row. 
\end{frame}

\begin{frame}[fragile]{Matrix Operations}

These are the available matrix operations in Matlab:
\begin{table}[htdp]
\begin{center}\begin{tabular}{|cc|} \hline
$+$ & addition \\
$-$ & subtraction \\
$\ast$ & multiplication \\
$\hat{}$ & power \\
$'$ & (conjugate) transpose \\
$\backslash$ & left division \\
$/$ & right division \\\hline
\end{tabular}
\end{center}
\label{defaulttable}
\end{table}
The matrix division operations need a special comment\dots
\end{frame}

\begin{frame}[fragile]{Matrix Division}
Matrix division is how you solve linear systems that aren't too big. If $A$ is invertible and $b$ is a solution vector, then
\begin{itemize}
\item \verb+x=A\b+ is the solution to $Ax=b$. 
\item \verb+x=b/A+ is the solution to $xA=b$. 
\end{itemize}

\textcolor{red}{Do NOT use \texttt{x=inv(A)*b}!} 

The $\backslash$ operator is pretty smart:
\begin{itemize}
\item If $A$ is square, then $\backslash$ tries a Cholesky factorization, then an LU factorization with Gaussian Elimination if necessary to solve the system.
\item If $A$ is not square, then $\backslash$ uses a QR factorization to solve the over/under determined system in the least squares sense.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Array Operations}
The matrix operations $+$ and $-$ already operate element-wise, but the others do not. So \texttt{A*B} is matrix multiplication, not element-wise multiplication. All the other operations can be made element-wise by putting a dot before them. Examples:

\begin{itemize}
\item \verb+[1,2,3,4].*[1,2,3,4]+; (this wouldn't make sense without the dot!)
\item \verb+[1,2,3,4].^2+
\item \verb+A.*B+ is $(AB)_{ij}=A_{ij} \cdot B_{ij}$.
\end{itemize}

Dimensions have to match. These ideas are particularly useful when making graphics or simply plotting functions.
\end{frame}

\begin{frame}{Matrix Building Functions}
Chances are you'll have to use at least one of these functions at least once\dots
\begin{table}[htdp]
\begin{center}\begin{tabular}{|cc|} \hline 
\texttt{eye} & identity matrix \\
\texttt{zeros} & matrix of zeros \\
\texttt{ones} & matrix of ones \\
\texttt{diag} & create or extract a diagonal \\
\texttt{triu} & upper triangular portion of a matrix \\
\texttt{tril} & lower triangular portion of a matrix \\
\texttt{rand} & random matrix \\
\texttt{toeplitz} & toeplitz matrix\\
\texttt{meshgrid} & $X$ and $Y$ arrays for 3D plots \\\hline
\end{tabular}
\end{center}
\label{defaulttable}
\end{table}

For example, \texttt{zeros(m,n)} creates an $m$ by $n$ zeros matrix and \texttt{zeros(n)} creates an $n$ by $n$ matrix. To match the size of another matrix, you can do \texttt{zeros(size(A))}.
\end{frame}

\begin{frame}[fragile]{for, while, if relations}
Matlab flow control works nearly the same in every other programming language. 

A \texttt{for} loop repeats a group of statements for a \emph{fixed} number of times.
\begin{lstlisting}
for m=1:100
  num=1/(m+1);
end
\end{lstlisting}

A \texttt{while} loop executes until some condition is no longer satisfied:
\begin{lstlisting}
v=1; num=1; i=1;
while num < 10000
 num=2^i;
 v=[v; num];
 i=i+1;
end
\end{lstlisting}


\end{frame}

\begin{frame}[fragile]{for, while, if relations}
\texttt{if} relations are fairly straightforward.

\begin{itemize}
\item \texttt{if} \emph{condition} \\
\quad \emph{statements} \\
\texttt{end}
\end{itemize}
You can also test more than one statement with \texttt{elseif}:
\begin{itemize}
\item \texttt{if} \emph{condition} \\
\quad \emph{statements} \\
\texttt{elseif} \emph{other conditions} \\
\quad \emph{other statements} \\
\texttt{end}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Relations}
The relational operations in MATLAB are
\begin{table}[htdp]
\begin{center}\begin{tabular}{|cc|}\hline
$<$ & less than \\
$>$ & greater than \\
$<=$ & less than or equal \\
$>=$ & greater than or equal \\
$==$ & equal \\
$\sim =$ & not division \\\hline
\& & and \\
$\mid$ & or \\
$\sim$ & not \\\hline
\end{tabular}
\end{center}
\label{defaulttable}
\end{table}
\end{frame}

\begin{frame}{Relations}
When applied to scalars, a relation returns 1 or 0. When applied to matrices of the same size, a relation returns a matrix of 0's and 1's giving the value of the relation at each entry. So if you wanted to execute a statement when two matrices $A$ and $B$ are equal, you could use

\begin{itemize}
\item \texttt{if A==B; foo; end}
\end{itemize}

But if you wanted to do something when $A$ and $B$ were not equal, the relation would be
\begin{itemize}
\item \texttt{if any(any(A$\sim$=B)); foo; end}
\end{itemize}
The functions \texttt{any} and \texttt{all} can be creatively used to reduce matrix relations to vector or scalar relations.
\end{frame}

\begin{frame}{Scalar Functions}
Certain functions operate essentially on scalars, but operate element-wise when applied to a matrix. The most common functions are
\begin{table}[htb]
\begin{tabular}{|ccccc|} \hline
sin & asin & exp & abs & round \\
cos & acos & log (natural log) & sqrt & floor \\
tan & atan & rem (remainder) & sign & ceil \\\hline
\end{tabular}
\end{table}
\end{frame}

\begin{frame}{Vector Functions}
Other functions operate on vectors, though on matrices these functions act on each column separately. If you wanted row-by-row action, you would operate on the transpose of the matrix. Some of the more useful functions are
\begin{table}[htb]
\begin{tabular}{|ccccc|} \hline
max & sum & median & any & \\
min & prod & mean & all &\\
sort & cumsum & std & linspace &\\
length & cumprod & & & \\\hline
\end{tabular}
\end{table}
So the maximum element in a matrix $A$ is given by $\texttt{max(max(A))}$ instead of $\texttt{max(A)}$, which would return the largest entry in each column of $A$. 
\end{frame}

\begin{frame}{Matrix Functions}
Matlab stands for Matrix Laboratory, so it is no surprise that much of Matlab's power comes from its matrix functions. Some of the most commonly used are
\begin{table}[htb]
\begin{tabular}{|cc|} \hline
eig & eigenvalues and eigenvectors \\
det & determinant \\
inv & inverse (\textcolor{red}{avoid!}) \\
rank & numerical rank estimate \\
rref & reduced row echelon form \\
poly & characteristic polynomial \\
sqrtm & matrix square root \\
expm & matrix exponential \\\hline
lu & LU factorization \\
qr & QR factorization \\
svd & singular value decomp \\\hline
\end{tabular}
\end{table}

Note that many Matlab commands have multiple outputs. So \texttt{y=eig(A)} gives the eigenvalues, but \texttt{[v,d]=eig(A)} gives you both the eigenvalues and eigenvectors!

\end{frame}

\begin{frame}[fragile]{Colon notation, submatrices, and vectorization}
\begin{itemize}
\item Vectors and submatrices are often used to do some fairly complex data manipulation.
\item Vectorization can dramatically speed up your code, so learn how to use it! Many \texttt{for} loops aren't really needed.
\begin{itemize}
\item Compare \verb+J=sum(sum((data-model).^2))+ with \verb+r=data-model; J=r'*r;+
\end{itemize}
\item Using \verb+0.2:0.2:1.2+ creates the vector \verb+[0.2, 0.4, 0.6, 0.8, 1.2]+
\item and \verb+5:-1:0+ gives \verb+[5 4 3 2 1 0]+.
\item The colon notation can be used to access submats of a matrix. 
\begin{itemize}
\item \verb+A(1:4,3)+ is the first \emph{four} entries of the \emph{third} column of $A$.
\end{itemize}
\end{itemize}

\end{frame}

\begin{frame}[fragile]{Colon notation, submatrices, and vectorization}
\begin{itemize}
\item A colon by itself denotes an entire row or column.
\begin{itemize}
\item \verb+A(:,3)+ is the third column of $A$, \verb+A(1:4,:)+ is the first four rows.
\end{itemize}
\item Arbitrary integer vectors can be used as subscripts
\begin{itemize}
\item \verb+A(:,[2 4])+ contains as columns, columns 2 and 4 of $A$.
\end{itemize}
\item You can also do assignments with this notation
\begin{itemize}
\item \verb+A(:,[2 4 5])=B(:,1:3)+ replaces columns 2,4,5 of $A$ with the first three cols of $B$.
\end{itemize}
\item Also useful here: \verb+flipud(x)+ and \verb+fliplr(x)+ where $x$ is an $n-$vector.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{M-files: script and functions}
Most of your work will be in an m-file. There are two kinds of m-files: script files, and function files.

\begin{itemize}
\item A script file is just a sequence of normal Matlab commands. After you run the script file, you have access to all of the variables that were used -- this is the \emph{stack}.
\begin{itemize}
\item Variables in the script file are global and will change the value of variables of the same name in the current session.
\end{itemize}
\item Function files take an input and give an output. The stack is local, but can be made global (see \verb+help global+).
\begin{itemize}
\item Syntax for the first line: \verb+function output=funcname(inputs)+
\end{itemize}
\item Useful objects when coding functions:
\begin{itemize}
\item \verb+nargin, vargin, nargout+
\end{itemize}
\item Run the file by typing its name at the command line, or by pushing play in the editor.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Graphics and Plots}
We'll just do a quick intro here. The main visualization commands in Matlab are \verb+plot, plot3, mesh,+ and \verb+surf+. Read the documentation for each of these for all of the different plotting options. Also, type \verb+demo matlab graphics+ for a full tour of Matlab graphics.

\begin{itemize}
\item \verb+plot+ creates linear line plots. For instance, to plot $y=e^{-x^2}$ over the domain $[-1.5,1.5]$, you could use \verb+x=-1.5:.01:1.5; y=exp(-x.^2); plot(x,y);+ Note the element wise exponentiation!
\item Parametric plots are also easy to do. For example: \verb+t=0:.01:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)+
\item \verb+semilogy, semilogx, loglog+ produces log plots.
\item \verb+mesh+ and \verb+surf+ produce 3D surface plots. See the Matlab crash course for demos.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Graphics and Plots}
Of course graphs can be given titles, axes labled, and axes changed. Here are some commands to do just that.
\begin{table}[htb]
\begin{tabular}{|cc|} \hline
title & graph title \\
xlabel & $x$-axis label \\
ylabel & $y$-axis label \\\hline
axis([$x_{min}, x_{max}, y_{min}, y_{max}$]) & set axis to these limits\\
ylim([$y_{min},y_{max}$]); & set the $y$- limits \\
xlim([$x_{min},x_{max}$]); & set the $x$- limits \\
axis square & square up the axes \\
axis equal & even up the axes \\
axis on/off & turn on/off axes \\\hline
\end{tabular}
\end{table}
Use the axes command after you build the plot. The labels take strings as inputs. Example: \verb+title(`my awesome plot');+
\end{frame}

\begin{frame}[fragile]{Graphics and Plots}
More than one plot in one figure! You sure can! Some code snippets to do just that... In Matlab there is typically more than one way to do things. Each has its own benefits and drawbacks. Let's name some.
\begin{lstlisting}
x=0:.01:2*pi;
y1=sin(x); y2=sin(2*x); y3=sin(4*x);
plot(x,y1,x,y2,x,y3);
\end{lstlisting}
\vspace{-0.5cm}
\begin{lstlisting}
x=0:.01:2*pi;
Y=[sin(x)', sin(2*x)', sin(4*x)'];
plot(x,Y);
\end{lstlisting}
\vspace{-0.5cm}
\begin{lstlisting}
x=0:.01:2*pi;
y1=sin(x); y2=sin(2*x); y3=sin(4*x);
plot(x,y1)
hold on; plot(x,y2); plot(x,y3);
\end{lstlisting}

\end{frame}

\begin{frame}{Solving Ordinary Differential Equations}
Matlab has a range of functions for solving initial value problems of the form
$$
\frac{d}{dt}y(t) = f(t,y(t)), \qquad y(t_0)=y_0,
$$
where $t$ is a scalar, $y(t) \in \R^m$ is unknown, and $f(t,y(t)) \in \R^m$. 
\begin{itemize}
\item The function $f$ defines the ODE, and the IC $y(t_0)=y_0$ defines an initial value problem.
\item The simplest way to solve is to write a function that evaluates the right hand side, and then call one of the available ODE solvers.
\item Many options are available to tune the performance of the integrator.
\end{itemize}
\end{frame}

\begin{frame}[fragile]{ODE Example -- First Order}
To solve the scalar ODE
$$
\dot y(t)=-y(t)-5e^{-t}\sin 5t, \qquad y(0)=1
$$
for $0 \le t \le 3$ with \texttt{ode45}, we create an odefile \texttt{my.f} containing
\begin{lstlisting}
function yprime=myf(t,y)
   yprime=-y-5*exp(-t)*sin(5*t)
\end{lstlisting}
and then type
\vspace{-.5cm}
\begin{lstlisting}
tspan=[0 3]; yzero=1; 
[t,y]=ode45(@myf,tspan,yzero);
plot(t,y,'*--'); xlabel t; ylabel y(t);
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{ODE Example -- Higher Order}
Higher order ODEs can be solved only if they are first rewritten as a system of first order equations. For example, consider the pendulum equation,
$$
\frac{d^2}{dt^2}\theta(t) + \sin \theta(t) = 0.
$$

Defining $y_1(t) = \theta (t)$ and $y_2(t) = \frac{d \theta(t)}{dt}$ gives us a new system
\begin{align*}
\dot y_1(t) &= y_2 (t) \\
\dot y_2(t) &= -\sin y_1(t)
\end{align*}
This is something that we can code up for use by $\texttt{ode45}$ in a function \texttt{pend}, as follows.
\end{frame}

\begin{frame}[fragile]{ODE Example -- Higher Order}
\begin{lstlisting}
function ydot = pend(t,y)
   yprime=[y(2);
           -sin(y(1))];
\end{lstlisting}

The following commands compute solutions over $0\le t \le 10$ for a given initial condition. Since we are solving a system, in the output \texttt{[t,y]} the \texttt{i}th row of the matrix \texttt{y} approximates $(y_1(t),y_2(t))$ at time $t=$\texttt{t(i)}.

\begin{lstlisting}
tspan=[0 10];
yzero=[1;1];
[t,y]=ode45(@pend,tspan,yzero)
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Solving Ordinary Differential Equations}
The general form of a call to \texttt{ode45} is 
\begin{verbatim}
[t,y]=ode45(@fun,tspan,yzero,options,p1,p2,...)
\end{verbatim}
where the arguments \verb+p1,p2,...+ are parameters that will be passed to the ODE function. 
\begin{itemize}
\item There are many other ODE integrators: \verb+ode23, ode15s, ode113+. \verb+ode45+ is usually a good place to start though.
\item The ODE options offer a lot. Don't pretend they're not there. 
\end{itemize}
\end{frame}

\begin{frame}{Optimization \& Least Squares}
Most generally, optimization involves iteratively finding the minimum of a vector valued function. These problems are everywhere in applied mathematics, and they take the form of
$$
x^\ast = \min_{x \in \Omega} f(x)
$$
Least squares problems arise in data fitting, parameter estimation, and look like
$$
\min_{x\in \Omega} \|Ax-b\|^2_2
$$
if linear least squares, and
$$
\min_{x\in \Omega} \|F(x)\|^2_2
$$
if nonlinear. 
\end{frame}

\begin{frame}{Optimization \& Least Squares}
This is how to get started.
\begin{itemize}
\item Define a cost function from $\R^m$ to $\R$.
\item Pick an algorithm or method to minimize the cost.
\end{itemize}

For example, if one wanted to find the parameters $q$ to a model defined by a set of DE's that best fit collected data; one method that \emph{may work} is as follows

\begin{enumerate}
\item Given a guess for the parameter, $q_0$, solve the model at that parameter.
\item Given the model output, compare to the data. That is, compute the cost. Say, with a function that looks like
$$
J(q)=\sum_{i=1}^N (model(q)_i-data_i)^2
$$
\item Repeat with a better guess based on the result. (Let the algorithm do the work).
\end{enumerate}
\end{frame}

\begin{frame}{Optimization \& Least Squares}
The Optimization Toolbox in Matlab can help out with these problems.

\begin{itemize}
\item fminsearch
\item fmincon
\item fminunc
\item lsqnonlin
\item lsqnonneg
\end{itemize}

Also, google for Tim Kelley. Lots of optimization software available from his site.
\end{frame}

\begin{frame}{There. Is. So. Much. More.}
The only way to really learn Matlab is to figure things out as you need them. Or be like me and subscribe to the Matlab newsgroup, read the Matlab blogs, enter the Matlab programming contests\dots But you should definitely look up and read about:

\begin{itemize}
\item anonymous functions and subfunctions!
\item structure and cell arrays!
\item multi-dimensional arrays!
\item numerical integration aka quadrature!
\item sparse matrix operations!
\item how to work with strings and parse data files!
\item handle graphics (scary)!
\end{itemize}


\end{frame}
\end{document}