%% Matlab Tutorial Script - Session 1 
% (c) 2011 David Weiss

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Basic Basics (In Person)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% 1 Cover GUI, basic mechanics of how to use the Matlab Desktop software:
%{
   - Command Window
   - Command History
   - Workspace
   - Documentation
   - Editor (enabling Cell Mode)
%}

%% 2 Using matlab as a calculator.
clear all;

% Try running these commands individually.
2+2
x = 2
y = 5
x+y
x*y
z
log(x)
exp(x)

x = 5; % suppress output with semi-colons
log(x)

%% 3 Getting help on commands.

% Load documentation for "log" command.
doc log

% Load documentation for "sort."
doc sort

% Load documentation for basic plots.
doc plot

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% 4 Basic matrix creation; every variable is by default a matrix.

x = 5;

%% 5 Dealing with dimensions, how do you work with matrices?

% ndims(x) --- get # of dimensions of x
% size(x) -- get the size of each dimension of an n-dimensional array

% every variable is at least a 1 X 1 2-d matrix!
ndims(x) 
size(x) 


% manually specific matrix entries with [ ... ]
y = [1 2 3]

% divide rows with ; or newlines
y = [1 2 3; 4 5 6]
y = [1 2 3
    4 5 6]
y = [1 2 3 ... % elipses (...) breaks lines without breaking commands
    4 5 6]

% basic matrix initializations:
x = ones(3, 5)
x = zeros(3, 5)
x = nan(3, 5)
x = inf(3, 5)
x = eye(5)

% length vs. size vs. numel
size(x)     % [ rows, cols, ... ]
length(x)   % size of largest dimension
numel(x)    % number of elements

%% 6 Block matrix creation and numeric series.

% shortcuts to generate standard random matrices
x = rand(3, 5)   % uniform(0,1)
x = randn(3 ,5)  % normal(0,1)

A = round(rand(2) * 10)  % EXERCISE: what does this command do?
At = A'     % transposition!! very important.

B = eye(3);

C = [A At; At A] % block matrix specification

D = [A A]
D = horzcat(A, A)

E = [B; B]
E = vertcat(B, B)

F = repmat(A, [2 3])  % arbitrary replication of matrices

x = 1:10
x = 1:2:10  % start:stepsize:end

x = 1:-1:10 % what will happen?

% any step size works!
x = 10:-1:1
x = 0:0.1:1

%% 7 Matlab = Matrix Laboratory; Performing operations on data.

A = 2*ones(4)
A + A % matrix addition
A + 1 
A*A  % linear algebra: matrix multiplication
A' % matrix transpose
A.*A % element-wise multiplication

A./A % element-wise division
A.^A % element-wise power

% functions: take in input, apply processing, produce output:
 
log(A) % element-wise logarithm (natural)
exp(A) % element-wise exponentiate (natural)

% How to resize data:
A = 1:24
B = reshape(A, [4 6]) % note: Matlab counts down columns, then across rows
C = reshape(A, [6 4])

% EXERCISE: is size(B) == size(C)? are the values B' and C the same? 

% what happens if dimensions don't match?
D = reshape(A, [5 5])


%% 8 Commands that operate over dimensions (vectorizing commands)

sum(A) % VECTORIZING operation: coverts matrix to vectors, vectors to scalars
sum(A, 1) % operate OVER rows; produce 1 VALUE PER ROW
sum(A, 2) % operate OVER columns; produce 1 VALUE PER COLUMN

% REMEMBER: USE doc COMMAND TO FIGURE OUT WHAT FUNCTIONS DO

% EXERCISE: What is size(sum(A,1))? what is size(sum(A,2))?
 
% common mistake: forgetting that + requires equal size operands.
A + sum(A, 1) % EXERCISE: Why is this wrong?

%% 9 Accessing (indexing) parts of matrices.

x = 10 - (1:6);  % note: priority of 

x(1:3) % Get elements #1-3 from x
x(4:end) % Get the 4th through last element from x

% Indexing works like this: 4:end is converted to [4 5 6], then
% Matlab evaluates x([4 5 6]). 4:end is just shorthand.
x([4 5 6])
y = [4 5 6]

%% 10 Logical indexing.

% logical commands >, ==, < distribute over elements in
% matrices. 1 = true, 0 = false.
x > 5
x == 7

% Convert logical values to indexes using 'find'.
find(x>5)
find(x==7)

x(find(x==7))
x(find(x>5))

% Matlab will convert automatically for you if the sizes match.
x(x==7)
x(x>5)

% Indexing works linearly or by subscripts.
B = reshape(1:24, [4 6]);

B(1:4) % get elements #1:4 in B.
B(:,1:4) % get columns 1:4 in B
B(2:3, 1:4) % get submatrix from rows 2,3, columns 1:4 in B.

% assignment works 
B(B<15) = 0

% EXERCISE: Figure out what this command is doing.
B(B<15) = rand(numel(find(B<15)), 1) 

% What is the difference between double(0) and false?
class(double(0))
class(false)
class(1<0)

%% 12 Saving and loading the workspace. 
B = rand(5);
C = rand(10);

save workspace.mat % saves everything in workspace
load workspace.mat % re-loads everything
save workspace.mat B C % saves only B and C
load workspace.mat B  % loads only B

%% 13 Saving and loading matrices into various formats.

% save matrix data to text files.
save Btext.txt -ascii -tabs B
load Btext.txt  
Btext % loading from textcreates variable named after file

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Control Logic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% 14 What is a for loop? 

% For loops: run the same command for every specified value of the
% variable.
for i = 1:10
    i
end

% Add up everything in a vector
a = 1:5
s = 0
for i = 1:numel(a)
    s = s + a(i)
end
s

% How does this compare to sum()? hint: always use sum instead
sum(a)

%% 15 If statements and while statements

% While loops: run the same command as long as the expression evaluates to
% true.
i = 0
while i < 10
    i = i + 1
end

i = 3
if i < 5
    % Do something once only if i < 5
    x = sum(a)
else
    % Do something otherwise.
    x = 5
end

% You can combine logical statements and if statements
if i < 5 & i > 2
    i
end

% This is equivalent to nesting if statements.
if i < 5
    if i > 2
        i
    end
end
        
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Plotting
%%%%%%%%%%%%%%%%%%%%%%%%%%%%    

%% 17 Basic line plots.

x = -pi:0.1:pi;

% Plot a sine curve
plot(sin(x))

% Plot a sine curve, where we specify both x and y values.
plot(x, sin(x))

% Now we also specify how it should be drawn.
plot(x, sin(x), '-ro')

% See the PLOT command documentaiton for help.
doc plot

%% 18 Creating and closing figures.

figure(1); % Create another plotting area
plot(x, sin(x))
figure(2);
plot(x, cos(x));

% close figure 1
close(1);

% close all open figures
close('all');

%% 19 Using "hold on" and "hold off"

% Use 'hold' command to allow to draw on an existing plot.
plot(x, sin(x), '-ro');
hold on;
plot(x, cos(x), '-bx')
plot(x, tan(x), '-g.')
hold off;

%% 20 Annotating the plot.

% Manually specify axes.
ylim([-1 1]);

% Use 'legend' when you have multiple lines.
legend({'Sin', 'Cos', 'Tan'});

% Another way of plotting multiple lines: pass in a matrix.
figure();
plot(x, [sin(x)' cos(x)' tan(x)']);  % EXERCISE: Why do I need to transpose?
legend({'Sin','Cos','Tan'})
ylim([-2 2]);

%% 21 Histograms and bar charts.
figure('Name', 'Histogram Plot');
hist(randn(10000,1), 100); % Histogram with 100 bins.

% EXERCISE: Figure out what this plot command does for bar charts.
bar([sin(-5:1:5)' cos(-5:1:5)']) % Why do we need to transpose?
legend({'Sin', 'Cos'});

%% 22 Printing plots to images and PDF.

% Print the current plot to a JPEG image with 72 dpi resolution.
hist(randn(10000,1), 100); % Histogram with 100 bins.
print -djpeg -r72 histogram.jpg

% Print the current plot to PDF
bar([sin(-5:1:5)' cos(-5:1:5)']) % Why do we need to transpose?
legend({'Sin', 'Cos'});
print -dpdf barchart.pdf

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Other data types
%%%%%%%%%%%%%%%%%%%%%%%%%%%%    

%% 23 Strings and character data

% A string is an array of characters. We create strings by using single
% quotes.
str = 'this is a string variable'

% A string is a matrix too
str(1)
str(2)
str(5:end)

% A char is just a number that corresponds to a number. We convert numbers
% to letters, and vice versa.
double(str)
char(str-1)

% EXERCISE: Try to decode this string into readable text using numeric
% operations.
decode_string = 'Bï¿½ï¿½@ï¿½ï¿½ï¿½@ï¿½ï¿½ï¿½@Bï¿½ï¿½ï¿½ï¿½ï¿½ï¿½'

%% 23 Mixing multiple data types with cell arrays
clear

% if strings are arrays, how to make array of strings? answer: CELL arrays.
a = {'string 1', 'string 2', 'string 3'}

% cell arrays: organize multiple variables of different types into an
% array. use {} instead of () to access.
c{1} = rand(3)
c{2} = 'i am cell #2'
c{2,1} = rand(10)

%% 24 Mixing multiple data types with struct arrays.

% structs: a convenient way of organizing multiple variables of different
% types
s.a = rand(5)
s.b = rand(3)
s.c = rand(10)
s.d = 'hello!'

% structs organize multiple variables by name. to access them, you need the
% proper name.
s.d

% structs are useful for storing parameters of a model, e.g.
model.theta = 5
model.alpha = -1
model.verbose = true
model.fit = 3

