% MATLAB basics
% 
% MATLAB = MATrix LABoratory
% 
% Starting MATLAB
% 	command window
% 	workspace
% 	command history
% 
% MATLAB as a calculator
1+1
2*3
1-2*3
(1-2)*3
1+2*3^4
((1+2)*3)^4
1*2/3
pi
sin(1)
asin(1/sqrt(2))
1/81
1/81*1000
% 
% Exponentiation has the highest precedence, 
% followed by multiplication and division, 
% followed by addition and subtraction. 
% Expressions are otherwise evaluated left to right. 
% Parentheses alter the precedence, 
% with the usual precedence applied within each set of parentheses
% 
format short
format long
format short e % or format shortE
format long e % or format longE
% 
% Special Functions and Values
pi 
e=exp(1)
log(e)
% log is the natural log. 
% If you want a different base, try 'help log'
% sin, cos, tan, sec, csc, cot, asin, etc.
% %
% Everything to the right of % is treated as a comment.
% 
% 
% Using variables
% A variable is a means of storing numbers (information).
% An array is a means of storing a sequence of numbers.
% 
a=2
b=4
c=a*b
d=a^b
e=cos(d)

%Formatted printing: 
fprintf('%4u square equals %4u \r', a, b)
fprintf('%4u cube equals %4u \r', a, c)
fprintf('The square root of %2u is %6.4f \r', b, a)

%Remarks: the command "fprintf" is for formatted output, using the format specified in
%the first string '...' in the parentheses. For example, the "%4u" (4-digit integer) and "%6.4f" (real
%number that preserves 4 digits to the right of the floating point) are the format for the
%variable(s) for output. 
% 
who
% 
% semicolon suppresses output
f=csc(pi/2);
f
% 
% variable names are case sensitive
A=5
a
A
% 
% There are certain reserved words that cannot be used as variable names, 
% e.g. pi.
clear  % removes all variable definitions
clear b
b
% command "clear all" clears all!
% 
% Continue a line with three periods in succession
a = 3+b-...
d
% 
% uparrow and downarrow scroll backwards and forwards through command
% forward arrow and backward arrow move cursor along command line.
% 
% Return   with the cursor at any location executes command.
% Escape   erases command.
% Ctrl+C   stops calculation.
% 
clc	 % clears screen.
quit % exits Matlab.
exit % also exits Matlab.
help % getting help with Matlab.
% 
% 
% 
% Arrays
a=[1 2 3 4 5]	
%OR	
a=[1,2,3,4,5]
whos
a(2)
a(3)
b=[2 3 5 7 11 13 17 19];
b(4)
% 
% You can change entries in an array using the array editor.
% 
% Operations with arrays
5*a
a/2
a*b
a(6)=6
a(7)=7
a(8)=8
a*b
a.*b
a.^2
a'*b
a*b'
% 
% Plotting
% 
help plot
a=[1:1:10];
b=5*a;
plot(a,b,'-')
hold on
c=2*a;
plot(a,c)
d=10*a;
plot(a,d);
title('Some straight lines')
xlabel('x')
ylabel('y')
hold off
% 
% Note: use command subplot if you need to place several graphs side to side!
%   
% Saving your work
% Saving workspace variables
% 
% In Command Window: >> save <filename>
% 
% Saves workspace variables into a file called filename.mat  
% This option does not save a command history, 
% it only saves values for variables that you have entered.
% 
% >> load <filename>
% 
% gets them back
% 
%  
% Recording your session: 
%
% >> diary ('filename.txt') 
% 
% Begins to log all commands and output into a file called filename.txt, 
% This file is stored in the MATLAB work folder  
% 
% >> diary off
% 
% Vectors and Matrices
%
% To create a row vector, make in same way you create an array
row=[1 2 5.4 -6.6]
% To create a column vector, use a semicolon to separate each element
column=[4;2;7;4]
% You can tell the difference between a row and column vector by looking in
% the workspace, displaying the variable, or using the size function
% length is also a useful function
%
% Matrices can be made like vectors
% Element by element
Mat=[ 1 2;3 4]
% Concatenating vectors of matrices (dimension matters)
a=[ 1 2];
b=[3 4];
c=[5;6];
d=[a;b];
e=[d c]

% Some useful matrix functions: zeros, ones, eye, rand

% Note: vector indexing starts at 1, not 0!
% Matrix entries can be accessed using subscripts
% Look up ind2sub and sub2ind in help to convert between subscripts and
% indices
e(2,1)
% Picking submatrices
e(1:2,2:3) %Specify contiguous submatrix
e([1 3], [2 3]) %Specify rows and columns

%To select rows or columns of a matrix, use :
e(1,:)
e(:,3)
e(2,:)=[3 6];

% Logical Variables
% Matlab uses logical variables or arrays 
% to denote a true or false statement using the numbers 1 and 0.
% 
% Example:
a = 40
a > 50
a < 10
a >= 39

% Matlab contains functions to help you find desired values: min, max, find

% Control Flow Statements 
% For loops:  Use for a known number of iterations
for j=1:10
    j
end
% 
for j=1:10
    5*j
end
% 
for j=1:10
    fprintf('hello guest %d\n', j)
end
% how many primes from 1 to 20?
number=0;
for j=1:20
    number=number+isprime(j);
end
number
% 
for j=0:5
    for k=0:9
        fprintf('%d%d\n',j,k)
    end
end
% 
for j=1:5
    A(j)=j;
end
A
% 
for j=1:5
    for k=1:5
        M(j,k)=j*k;
    end
end
M

% While loops: a more general for loop, don't need to know the number of
% iterations
%The command block will execute while the conditional expression is true
j=0;
while j<10
    j=j+3;
end
j
% 
numsteps=0;
tolerance=1;
while tolerance>0.01
   %do stuff
   tolerance=tolerance*1/2;
   numsteps=numsteps+1;
end

%  m-files
%  In order to save a command sequence, 
%  you will want to create an m-file.  
%  From the "File" menu, click on "New" and m-file.  
%  This will open an editor window.  
%  You can type commands here and save the file with a .m extension.
%  You can execute your saved file at any time 
%  by typing the name of the file (without the .m) in the command window.  
%  You can also execute the file by using the F5 button 
%  or the icon that looks like a down arrow next to a page.
%
% If you want to execute your m-file in a session logged with the diary
% command, type "echo" before executing the m-file. 
% (if you do not do it, the diary file will contain only the responses, 
% not the commands)

% Declare and using functions
% Example: create a new file and type
function output = myfunc(x); 
% evaluating function myfunc(x)
output = 1+1./x; 
% end if myfunc
% Save it as myfunc.m
% Call it (from command window or from other m-file):
myfunc(pi) 

%Another example: 
function y = plusone(x)
% calculate the sum of the given argument 'x' plus 1
% Arguments:
% x (input) value to be added to 1
% y (output) the result of the addition
y = x + 1;
% end of plusone function
%
%
%Solving linear equations
A = [1 2 3; 4 5 6; 7 8 0] % matrix of coefficients
Ainv = inv(A) % inverse matriX
% You can also use 
Ainv = A^-1
b = [2; 3; 7] % right-hand side vector in Ax = b 
x = Ainv*b % solution to Ax = b 
%Another (better) way to find x 
x = A\b
% or 
x = mldivide(A,b)
%
% Determinant of A
det(A)
%
% If a matrix is singular or close to singular
B = [1 2 3; 4 5 6; 7 8 9]
det(B)
inv(B)
%
C = [0 2 -1; 3 -2 1; 3 2 -1]
det(C)
inv(C)
%
%  Underdetermined systems systems
A = [1 2 3; 4 5 6]
b = [2; 4]
x = A\b
%
% Some matrix decompositions
B = [1 2 3; 4 5 6; 7 8 9]
% QR decomposition
[Q,R] = qr(B)
% SVD: singular values decomposition  
[U,S,V] = svd(B)
%
% Eigendecomposition 
A = [0 -0.5 -1.5; 1 1.5 1.5; -1 0.5 0.5]
[V, E] = eig(A) %A is diagonalizable, i.e., A is similar to a diagonal matrix E, 
% and there exists V, s.t. A = V*E*V^-1 
A = V*E*inv(V)
%
D = [3 1 0; 0 3 1; 0 0 3] %(this matrix is not diagonalizable!)
[V, E] = eig(D) % 
D = V*E*inv(V)
%
%
% Some other useful commands:
% Recall 1:10 results in 1 2 3 4 5 6 7 8 9 10.  
% The command 1:2:10 results in 1 3 5 7 9.
% It's useful in for loops to sometimes use something like 10:-1:1, 
% which gives 10,9,8,...,1.
% The command rand(1,10) gives an array of random numbers between 0 and 10.
% To create an empty array called myarray, type
% myarray = []
% 
% Machine Epsilon:
% Computers can differentiate between numbers up to a certain precision.  
% The command "eps" gives the gap between 1 and the next larger 
% floating point number number.
