%% MATLAB Tutorial
% The following is a tutorial on useful matlab commands and features, as well as an example of how to use live scripts. This tutorial includes:
% Variables
% Matrices
% Matrix operations
% Matrix functions
% 2D plots
% 3D plots
% Excercises
%
%% Introduction
% The name MATLAB comes from the concatenation of Matrix and Laboratory, meaning a computational environment for matrices, i.e., rectangular arrays of numbers. As such, the language is matrix-based. Vectors are represented by one-dimensional matrices, and scalars are 1x1 matrices. This has implications on syntax as well as plotting functions. MATLAB has a computational engine as well as a programming language, specifically an interpreted language that is executed directly by the computational engine (without needing to be compiled first). A program can be thought of a sequence of commands, and can either be typed into the command prompt or stored in files, with a .m extension. These files can either be scripts, which are just a collection of commands, or function files, which contain functions, i.e., a collection of commands that has its own scope (thus often requiring input and output variables to communicate with other programs or the command prompt). The newest file type is the LiveScript (.mlx) which has some typesetting features and can display output in the same page view as the script itself. This view can be exported to a pdf for assignment submission, and thus supercedes the publish feature of MATLAB scripts.
% This LiveScript contains examples of commonly used MATLAB commands as well as some practice exercises. The user can type directly into this file and execute (even modify) each line to test understanding.
%
%% Variables
% Most objects in MATLAB are matrices (there are other types, of course, such as structures and cell arrays). For example,

[ 1 2 3; 4 5 6]

% is a 3x2 matrix. Typing Ctrl-Enter in this section will execute the above command. Try: change one element of the matrix and execute the command.
%
% Notice that the displayed output begins with "ans =".  This is because MATLAB is saving the answer for future use by storing the matrix in a variable. We can give the variable a name ourselves by typing the following (if you hover your mouse over the squiggly underline below, you will see that one should generally not use ans as a variable name in practice as it is frequently over-ridden).

A = ans

% We can create other variables similarly

B = [ 3 2; 2 1]
c = 7

% For variable names, we can use words with uppercase or lowercase letters (but names are case-sensitive) and numbers. However variable names cannot start with a number.
%
% Try: fix the variable assignment below by giving the value a variable name.

21

%
% We can refer to the individual entries of a variable by specifying the row and column location (or range)

A(2,1)
A(1,1:2)
B(1,:)
c(1,1)

% Note that a colon by itself implies the entire range.
% We can also do assignment to submatrices of variables, for example, replacing the first two rows and columns of A with B


A(1:2,1:2)=B

% Note that this only works if the location and the values to be assigned have the same size. To check, we could ask

size(B)

%
%% Matrices
% Above we gave some examples of matrices (including the 1x1 matrix c). There are several built-in functions for creating special matrices such as an nxn identity, zero, or random matrix

I3 = eye(3) % I, get it? ;^)
Z4 = zeros(4)
R2 = rand(2)

% Try: re-execute the above several times to see multiple (different) realizations of the random matrix.
% Note: the zeros command is commonly used for efficiently pre-allocating memory in very large arrays. MATLAB will gladly continue to increase the size of an array (dynamically allocating memory) if you simply assign values to not-yet-existing entries, but continually doing this results in a slow proceedure.
% Each of the above commands is a function with multiple possible calling sequences. If one argument, say n, is given, the function will create an nxn matrix. If two arguments are given, say m and n, then an mxn matrix is formed. Type help rand, for example, to see all possibilities.

R23 = rand(2,3)

% The transpose of a (real) matrix is found by using the apostrophe (technically this is the conjugate transpose, but for real matrices these are the same)

R23'

% It is worth noting here that variables can have complex values and many of the built-in functions will work as expected, for example

size([1i 1; -1 -1i])

% We can also make matrices out of other matrices, for example

D3 = diag([1,2,4])

% puts the input matrix (vector) on the diagonal of a new matrix. With a different calling sequence, the super- or sub-diagonal could be specified.
% Try: what do you think diag(ones(3,1)) does?

%enter code here to check

%
% Matrices can also be implicitly defined by giving a range

1:5

% We have actually seen this syntax already above when displaying values in the first row of A, as in A(1,1:2). The second argument in that calling sequence is actually a matrix 1:2, i.e., [1 2]

A(1,[1 2])

% Thus we see that the colon operator can create (one dimensional) matrices consisting of integers between the first and second arguments given to it. (This notation is often used within the calling of for loops as well.) A slightly different calling sequence can specify an increment so that the result is not necessarily integer-valued

1:0.5:5

% A similar result can be achieved with the built-in command linspace, which specifies the first and last element, as well as the number of elements

linspace(1,5,9)

%
%% Matrix Operations
% MATLAB performs computations primarily based on efficient matrix operations, but also allows non-standard operations such as component-wise operations. The most common binary operations are matrix addition and multiplication.

A+A
B*A

% Matrix subtraction is also defined in the usual way. Matrix division, on the otherhand, is perhaps less intuitive. The operator is called backslash, denoted B\A, or equivalently mldivide(B,A), which is roughly B^{-1} \text{ }A\ldotp

B\A

% Try: Solve R2 X = R23 using \.

%type your code here

%
% Another standard matrix operation is ^ (exponentiation), also known as matrix power (mpower).

B^2

%
%% Array Operations
% Component-wise operations are called array operations. For example, .* is array multiply and causes two matrices to be multiplied component-wise

B.*R2

% As with addition (which is naturally component-wise), the matrices must be the same size. Other array operations are ./ (right array divide) and .^ (array power)

B./R2 % this takes each element of B and divides it by the corresponding element of R2, it does not form a matrix inverse
B.^2 % this takes each element of B and squares it, it is not the same as B*B

%
%% Matrix-scalar Operations
% A third type of matrix operation is the matrix-scalar operation, which can be understood to be a generalization of scalar multiplication for matrices. In essence, if one of the inputs to a matrix operation is a scalar, then the operation is interpreted to be component-wise with respect to the matrix.

5*A
5+B
A/5

%
%% Matrix Functions
% Part of the efficiency of MATLAB is the ability to apply standard functions, including trigonometric functions, to arrays of numbers simultaneously, i.e., without needing for loops to iterate through the elements. Most standard functions in MATLAB accept matrix inputs and return matrix outputs of component-wise function evaluations.

t=linspace(0,pi,10)
y=sin(t)

% This will be especially useful for producing plots.
%
%% 2D Plots
% As with most other commands, MATLAB expects the inputs to a plot command to be matrices. Rather than attempting to deduce what resolution you would like for your plot, it requires you to give it the data you would like graphed.

plot(t,y)

% If you want better resolution, you should increase the length of the independent variable array

t100=linspace(0,pi,100);
y100=sin(t100);

% Note the use of the ; to supress the output of the rather long arrays.

plot(t100,y100)

%
% Plots can contain more than one curve (each with its own color and, optionally, symbol), legends, axes labels, titles, etc. See help plot for other plot options.

plot(t,exp(t).^2,'-o'); 
hold on; 
plot(t,exp(t.^2),'--s'); 
legend('exp(t)^2','exp(t^2)','Location','best')
title('Comparison of two exponential functions')
xlabel('t')
ylabel('y')
hold off

% Other types of plots can be useful for certain data, such as semilogx, semilogy, or loglog.

semilogy(t,exp(t).^2,'-o'); 
hold on; 
semilogy(t,exp(t.^2),'--s'); 
legend('exp(t)^2','exp(t^2)','Location','best')
title('Comparison of two exponential functions')
xlabel('t')
ylabel('log(y)')
hold off

%
%% 3D Plots
% Functions of two variables can be visualized with surface plots using the surf command. MATLAB again expects the coordinates of each data point, which in this case means three matrices, one for each coordinate in x, y, and z dimensions (however, it will allow vector arguments for x and y as long as the coordinates are x(j), y(i) and Z(i,j)).

x=-pi:0.05:pi;
y=0:0.01:1;
Z=y'*cos(x); % note the use of ' since y is a row vector, and we need the outer product
surf(x,y,Z) 
xlabel('x') 
ylabel('y') 
zlabel('z')

%
% Another type of 3D plot is plot3 which plots curves in space.  In each of these cases, the view can be changed directly with the view command, or using the rotate3d command.

t = 0:pi/50:4*pi;
plot3(sin(t),cos(t),t); 
rotate3d

%
%
%% Assignment
% Use the techniques described above to complete the following exercises:
% Exercise 1: Write MATLAB code to create a 5x5 matrix A with 2's on the diagonal, and -1 on the super- and sub-diagonal. Then replace the (1,1) element of A with a 1.
% (Make your commands capable of handling an arbitary sized NxN matrix by first defining N=5, then using the variable N as the size in each of the commands.)

% Put your code here

%
% Exercise 2: Write MATLAB code to create an N dimensional vector t with uniformly spaced numbers between 0 and \frac{\pi }{2}. Then create a vector y with the data f(t) where f\left(t\right)=6\text{ }\mathrm{sin}\left(t\right)-9\text{ }{\mathrm{sin}}^3 \left(t\right). Finally, multiply each entry of y by h^2, where h=\frac{\pi \text{ }}{2\left(N+1\right)}.

% Put your code here

%
% Exercise 3: Find the inverse of the matrix A. Describe the pattern that you see in the entries.

% Put your code here

% Put your observations here.
%
% Exercise 4: Solve the system of equations A x = y two different ways, first by multiplying y by the inverse of A (you may need to transpose y for the dimensions to be compatible), and second by using the backslash operator. Compare the two solutions by plotting each vs t on the same graph. (Note: if you use hold on, be sure to put hold off at the end.)

% Put your code here

%
% Exercise 5: Repeat all of the above exercises but with N=10, N=50 and then N=500.  (Either copy/paste all the commands here, or simply change N above and re-execute the sections.) What do you notice as you increase N? This code is actually an implementation of a finite difference approximation to the solution of a second order ordinary differential equation boundary value problem.  Can you guess the true solution?
%
% Put your answer here.