\documentclass{article}

\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphics}
\usepackage{listings}
\usepackage{tcolorbox}
\usepackage{verbatim}

\DeclareMathOperator*{\argmin}{arg\,min}

\marginparwidth 0pt
\oddsidemargin  0pt
\evensidemargin  0pt
\marginparsep 0pt
\topmargin   0pt
\textwidth   6.5in
\textheight  8.5in
\setlength{\parindent}{0em}

\newenvironment{packed_itemize}{
\begin{itemize}
  \setlength{\itemsep}{0pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
}{\end{itemize}}

\newenvironment{packed_enumerate}{
\begin{enumerate}
  \setlength{\itemsep}{1pt}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}
}{\end{enumerate}}

\definecolor{codeback}{RGB}{235,255,255}

\lstset{ %
language=Matlab,                % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
numbers=left,                   % where to put the line-numbers
numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
numbersep=10pt,                  % how far the line-numbers are from the code
backgroundcolor=\color{codeback},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
frame=single,           % adds a frame around the code
tabsize=2,          % sets default tabsize to 2 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
escapeinside={\%*}{*)}          % if you want to add a comment within your code
}

\begin{document}

\begin{center}
  \Huge{MATLAB Overview}\\
  \Large{MATH1070: Numerical Mathematical Analysis}
\end{center}
Location: http://people.sc.fsu.edu/$\sim$jburkardt/classes/math1070\_2019/matlab\_overview/matlab\_overview.pdf
\vskip 0.1in
\hrule
\vskip 0.1in

\begin{center}
  \includegraphics[scale=0.50]{matlab_logo.png}
  \vskip 0.1in
  {\it{The interactive MATLAB language lets us do computational experiments.}}
\end{center}
\vskip 0.1in

If you are completely new to MATLAB, then you should review the information at places like the MATHWORKS tutorial website:
{\bf{https://www.mathworks.com/support/learn-with-matlab-tutorials.html}}

\section{The Very Basics}

When you start MATLAB, you see a command window with a prompt sign 
\begin{lstlisting}
>>
\end{lstlisting}
This is where you type your commands.  
\vskip 0.1in
You can give simple arithmetic commands like {\tt{98-53}}, but most MATLAB
commands will involve computing something and storing the result in a named
variable.  Once a variable has a value, it can be used in later computations:
\begin{lstlisting}
>> x = 0.99
>> y = x * x   % This could also be written as x^2
\end{lstlisting}
Arithmetic operators include {\tt{+, -, *, /, \^{} }}.  Mathematical functions 
include {\tt{abs(), max(), min(), mod(), sqrt()}}, and trig functions like 
{\tt{sin(), cos()}}.
\vskip 0.1in
When a statement computes a value, that value will be printed to the command
window.  If this is not desired, simply terminate the statement with a semicolon.

\section{M Files}

While interactive access to MATLAB is useful, it is often necessary to enter
long complicated instructions.  In such a case, it is better to store these
instructions as an M file.  An M file can be created by any text editor, or
you can use MATLAB's editor by choosing the {\bf{NEW}} menu item and selecting
{\bf{Script}} or {\bf{Function}}.  You can type in your commands, and then
save the file, giving it a name, such as {\it{pde.m}}.  Once the file is saved,
you can run the commands in the file by typing its name, as in
\begin{lstlisting}
>> pde
\end{lstlisting}
\vskip 0.1in
or, if this is a function file, you might supply input and collect the
resulting output:
\begin{lstlisting}
result = lambert ( x )
\end{lstlisting}

\section{User Functions}

A user function can be created as an M file.  It usually has inputs, outputs, and
a function name.  As a simple example, we might want a function that evaluates
\begin{displaymath}
  y = \frac{1}{(x-0.3)^2+0.01} + \frac{1}{(x-0.9)^2+0.04} - 6.0
\end{displaymath}
We can create a MATLAB function {\it{hump.m}}, so that we only have
to type this formula correctly once.  Note that division is done with 
a period-slash, squaring is done with a ``period-caret'', and we have 
to be careful about the parentheses:
\begin{lstlisting}
function y = hump ( x )
  y = 1.0 ./ ( ( x - 0.3 ).^2 + 0.01 ) ...
    + 1.0 ./ ( ( x - 0.9 ).^2 + 0.04 ) ...
    - 6.0;
  return
end
\end{lstlisting}
Once we have created this function, we can evaluate it at 2.0 by writing {\tt{y=hump(2.0)}}, or get the value at a variable {\tt{x}} by writing 
{\tt{y=hump(x)}} and so on.
\vskip 0.1in
We can also pass in a whole vector of $x$ values, and get back the corresponding
list of $y$ results, which is perfect for plotting, and other applications.
The list of $x$ values can be created using {\tt{linspace(first, last, how-many}}:
\begin{lstlisting}
x = linspace ( 0.0, 2.0, 101 );
y = hump ( x );
plot ( x, y )
\end{lstlisting}

\section{Control}

If some statements are to be executed several times, use the {\tt{for}} loop:
\begin{lstlisting}
  fact = 1;
  for i = 1 : 10
    fact = fact * i;
  end
\end{lstlisting}
If some statements are to be executed only if a condition is true, use
an {\tt{if()}} staatement:
\begin{lstlisting}
  if ( mod ( n, p ) == 0 )
    n = n / p;
  end
\end{lstlisting}
More elaborate cases can add the {\tt{elseif()}} and {\tt{else}} statements:
\begin{lstlisting}
  if ( x > 0 )
    absx = x;
  elseif ( x < 0 )
    absx = -x;
  else
    absx = 0.0;
  end
\end{lstlisting}
If some statements are to be repeated until a condition is true, use the
{\tt{while()}} statement:
\begin{lstlisting}
  while ( 1.0 < x )
    x = x / 2.0;
  end
\end{lstlisting}
Typical conditions include:
\begin{lstlisting}
  if ( a == 1 )  % Note the double equals sign here!
  if ( b ~= 2 )  % Note the "twiddle" for "not"
  if ( c < 3 )
  if ( d >= 4 ) 
\end{lstlisting}

\section{Vectors}

A numerical vector $\vec{v}$ is stored as a MATLAB array.  Examples of 
creating numerical vectors in MATLAB:

\begin{lstlisting}
    q = []                 % Creates an empty vector
    r = rand ( 6, 1 )      % Column vector of random values
    s = randn ( 1, 5 )     % Row vector of normal random values
    t = ones ( 4, 1 )      % vector of 1's
    u = zeros ( 3, 1 )     % vector of 0's
    v = randperm ( 8 )     % random permutation of 12345678
    w = 10 : 20            % integers from 10 to 20
    x = linspace ( 0.0, 1.0, 7 )
    y = [ 1.1, 2.2, 3.3 ]  % row vector of 3 values
    z = [ 4.4; 5.5; 6.6 ]  % column vector of 3 values
\end{lstlisting}

  Row and column vectors are different objects in MATLAB.  
  A row vector has a shape (1,n), while a column vector has a shape (m,1).
  You can find the shape of any array with the {\bf{size()}} command:
\begin{lstlisting}
    size ( x )
\end{lstlisting}
  and you can save these values using a command like:
\begin{lstlisting}
    [ m, n ] = size ( x )
\end{lstlisting}
  The {\tt{length()}} command returns the number of elements of a vector; 
  for a row vector, it returns n, for a column vector, m;
  
  Each entry in a vector has an index; the first entry in the vector $a$ is {\tt{a(1)}}. 
  You can print, use, or alter any element of a vector by indexing it.
\begin{lstlisting}
    u(2) = 20
\end{lstlisting}
  A {\it{colon}} can be used to refer to a range of vector indices:
\begin{lstlisting}
    w(3:8)
\end{lstlisting}
  We can specify a stepsize between successive indexes:
\begin{lstlisting}
    w(3:2:8)
\end{lstlisting}
  Most arithmetic functions can be applied to a vector, giving a vector of results,
  such as {\tt{abs(x), cos(x), exp(x), log(x) sin(x), sqrt(x)}}.
  The {\bf{'}} operator will transpose a vector from one form to the other.
\begin{lstlisting}
    rt = r'
\end{lstlisting}
  Some functions return a single result based on all the vector values, such as
  {\tt{max(x), mean(x), min(x), norm(x), std(x), var(x)}}.
\vskip 0.1in
  For pairs of vectors, the operator '*' requests a form of the vector dot product.
  To get the desired scalar result, the vectors must be written so that their
  dimensions have the form (1xn) * (nx1), that is, row vector times column vector.
  If $x$ and $y$ are column vectors, as is common in mathematics convention, then the dot product 
  is $x'$ * $y$.  If both are row vectors, then the express x*y' is necessary.  
\vskip 0.1in
  When applied to vectors, the operations {\bf{*}}, {\bf{/}} and {\bf{\textasciicircum}} 
  can be preceded by a period, indicating
  that the operation is to be applied element by element, returning a vector of results.
\begin{lstlisting}
    x .* y <-- returns a vector of elementwise products.
    x ./ y <-- returns a vector of elementwise fractions.
    x .^ 2 <-- returns a vector of elementwise squares;
    x .^ y <-- returns a vector of elementwise powers
\end{lstlisting}

\section{Matrices}

  An $mxn$ numerical matrix can be stored in a MATLAB array.  There are many
  commands to create such arrays:
\begin{lstlisting}
    O = pascal ( 5 )
    Q = []
    R = rand ( 3, 4 )
    S = randi ( 5, 3 )
    T = randn ( 2, 2 )
    U = ones ( 5, 3 )
    V = zeros ( 4, 3 )
    W = eye ( 3, 3 )
    X = [ 1, 2, 3; 4, 5, 6 ]
    Y = [ 1, 2;
          3, 4 ]
    Z = magic ( 4 )
\end{lstlisting}
Note that MATLAB programmers typically use a capital letter to represent a matrix,
  
  The {\bf{size()}} command returns the array dimensions:
\begin{lstlisting}
    [ m, n ] = size ( x )
\end{lstlisting}    
  Matrix values are accessed by specifying the row and column index, 
  typically written as (i,j).
  You can print, use, or alter any element of a vector by indexing it.
\begin{lstlisting}
    U(2,1) = 20
\end{lstlisting}
  The colon can be used to select a portion of the array:
\begin{lstlisting}
    R(2,2)     % a single entry
    R(2,1:4)   % the second row
    R(1:2,3)   % part of the third column
    R(2:3,2:3) % a 2x2 submatrix
\end{lstlisting}
  Most arithmetic functions can be applied to an array, giving an array of results:
    abs(X), cos(X), exp(X), log(X), norm(X), sin(X), sqrt(X)
  The {\bf{'}} operator will transpose an array from one form to the other.
\begin{lstlisting}
    Xt = X'
\end{lstlisting}
  Some functions return a row vector of results, by applying the operation separately
  to each column, including {\tt{
    max(X), mean(X), min(X), std(X), var(X);}}
\vskip 0.1in
  To multiply a matrix A times a vector x, we write 
\begin{lstlisting}
  y=A*x
\end{lstlisting}
If A is $m \times n$, then x should be $n \times 1$ and the result y will be 
$m \times 1$.
\vskip 0.1in
To multiply a matrix A times a matrix B, we write 
\begin{lstlisting}
C = A * B
\end{lstlisting}
If A is $m \times n$, B must be $n \times o$, and C will have size $m \times o$.
\vskip 0.1in
In some cases, it may be necessary to use the transpose operator, writing expressions like
\begin{lstlisting}
  u=A'*x
  v=B*y'
  w=C'*z'
\end{lstlisting}
 
When applied to matrices, the operations {\bf{*}}, {\bf{/}} and 
{\bf{\textasciicircum}} can be prefaced by a dot to indicate 
that the operation is to be applied element by element, 
returning a matrix of results.
\begin{lstlisting}
    x .* y <-- returns a matrix of elementwise products.
    x ./ y <-- returns a matrix of elementwise fractions.
    x .^ 2 <-- returns a matrix of elementwise squares;
    x .^ y <-- returns a matrix of elementwise powers
\end{lstlisting}

\section{Linear Algebra}

  Scalar functions of a matrix include the condition number, determinant, and rank:
    {\tt{cond(A), det(A), rank(A)}},
  but only condition number is really useful and reliable;
\vskip 0.1in
  Vector functions include returning the diagonal elements of a matrix: {\tt{diag(A)}}.
\vskip 0.1in
  Matrix functions include the inverse, the LU factorization, the pseudoinverse,
  and the QR factorization: {\tt{inv(A), lu(A), pinv(A), qr(A)}}
  Note that computing the inverse matrix {\tt{inv(A)}} to solve a linear system
  is numerically unreliable and unnecessary.
\vskip 0.1in 
  The set of linear equations {\tt{A*x=b}} is often posed, with the vector x unknown.
  If A is nxn and nonsingular, while b is nx1, then a unique solution may be expected.
  MATLAB can provide that solution by the command
\begin{lstlisting}
    x = A \ b
\end{lstlisting}
\vskip 0.1in

\section{Reading and Writing Data Files}

Commands are availabe to save all of your data, or to restore it.
To save a single item {\tt{x}} item in a text file {\it{my\_x.txt}}:
\begin{lstlisting}
  save ( 'my_x.txt', '-ascii', 'x' )
\end{lstlisting}
and then restore it by
\begin{lstlisting}
  x = load ( 'my_x.txt' )
\end{lstlisting}
\vskip 0.1in
Similarly, a text file {\it{my\_data.txt}}, containing $m$ rows and $n$ 
columns of data, can be loaded into a MATLAB variable by 
\begin{lstlisting}
  A = load ( 'my_data.txt' )
\end{lstlisting}

\end{document}
