
% Intro to matlab

% Note: a good site for matlab info and tutorials:
% http://www.indiana.edu/~statmath/math/matlab/
% Also see MATLAB Primer, by Kermit Sigmon.

% (1) Help and basics
%%%%%%%%%%%%%%%%%%%%%%

% The symbol "%" is used in front of a comment.

% To get help type "help" (will give list of help topics) or "help topic"

% If you don't know the exact name of the topic or command you are looking for,
% type "lookfor keyword" (e.g., "lookfor regression")

% When writing a long matlab statement that exceeds a single row use ...
% to continue statement to next row.

% When using the command line, a ";" at the end means matlab will not
% display the result. If ";" is omitted then matlab will display result.

% Use the up-arrow to recall commands without retyping them (and down
arrow to go forward in commands).

% Other commands borrowed from emacs and/or tcsh:
% C-a moves to beginning of line (C-e for end), C-f moves forward a
% character (C-b moves back), C-d deletes a character, C-k deletes 
% the line to the right of the cursor, C-p goes back through the
% command history and C-n goes forward (equivalent to up and down arrows).

% Mac: to enter text from file to matlab command window, highlight
% text and press enter key.
% Apple-. terminates execution of a command


% (2) Objects in matlab -- the basic objects in matlab are scalars,
% vectors, and matrices...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Define a scalar
N=5

%  Define a row vector
v = [1 0 0]

%  Define a column vector
v = [1;2;3]
   
%  Transpose a vector (row to column or column to row)
v = v'

%  Define a vector in a certain range: v=start:stepsize:end
v=1:.5:3
V=pi*[-4:4]/4

% The empty vector
v=[]

%  Define a matrix 
m = [1 2 3; 4 5 6]

%  matrices in matlab are such that 1ST parameter is ROWS
%                                   2ND parameter is COLS 
%  Define a zeros/ones matrix/vector: zeros(numrows, numcols)
m=zeros(2,3)   
v=ones(1,3)  

%  The identity matrix
m=eye(3)

% Define a random matrix or vector: (see differences rand, randn)
v=rand(3,1) 

% Read data from a file:
% Create a file named matrix_data with the following 3 rows: 
% 2     3     4
% 5     6     7
% 1     2     3
load matrix_data 
matrix_data

% Access a vector or matrix: vector(number) or matrix(rownumber, columnnumber)
v=[1 2 3];
v(3)

m=[1 2 3; 4 5 6]
m(1,3)              %1st row, 3rd col

% Access a row/column of a matrix: matrix(rownum,:) matrix(:,colnum)
% : means all values in that row or column, or you can specify a range of vals.
m(2,:)    %2nd row
m(:,1)    %1st column

m(2,1:2)
m(1:2, 1:2)

% size of a matrix
size(m)
size(m,1)  %num rows
size(m,2)  %num columns

% we can create a new vector of zeros the same size as m

m1=zeros(size(m))

% what objects/variables have I defined: "who" or "whos"
who
whos

% (3) Simple operations on vectors and matrices
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% (A) Pointwise Operations:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% addition of vectors/matrices and multiplication by a scalar
% are done "element by element"
a=[1 2 3 4];
2*a, a/4
b=[5 6 7 8];
a+b
a-b

% But * / ^ are matrix operations and do not operate "element by element". 
% To make them pointwise, use a "." in front: .* ./ .^

point_sqrd = a .^2
point_mult= a.*b

% Matlab has a large number of built in functions, see p.7 matlab primer.
% some operate on each point of a vector/matrix:

log([1 2 3 4])
round([1.5 2; 2.2 3.1])

% (B) Vector Operations
%%%%%%%%%%%%%%%%%%%%%%%

% Built-in matlab functions that operate on a vector. If a matrix is given, 
% then operates on each column of matrix. Some examples:

a=[1 4 6 3]
sum(a)
mean(a)
var(a)
std(a)
max(a)
a=[1 2 3; 4 5 6]
mean(a)                      %mean of each column
max(a)                       %max of each column    
max(max([1 2 3; 4 5 6]))     %to obtain max of matrix


% (C) Matrix Operations:
%%%%%%%%%%%%%%%%%%%%%%%%

% matrix multiplication
% make sure sizes match- (i j) * (j k)

[1 2 3]  * [4 5 6]  % note error, sizes do not match...
size([1 2 3])
size([4 5 6])

[1 2 3] * [4 5 6]'  % row vector 1x3 times column vector 3x1 
                    % results in single number.
                    % also known as dot product or inner
                    % product of 2 vectors

[1 2 3]' * [4 5 6]  % column vector size 3x1 times row vector 1x3
                    % results in 3x3 matrix.
                    % also known as outer product of 2 vectors.
[4 5 6]' * [1 2 3]


a=[1 2; 3 4; 5 6]
b=[5 6 7];
size(a)
size(b)
b*a
a'*b'

% see matlab primer, p. 7, for matlab built-in matrix functions.

%(4) Saving your work
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% You can save all or some of the variables in your matlab
% session.

save mysession      %creates a file named session.mat with all vars

save mysession a b  %save only a and b
clear a b           %clear variables a and b

% To load session

load mysession
a
b

%(5) Relations and control statements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% relational operators: == (equal), ~= (not equal), <, <=, >, >=, etc.

% example: given a vector vec, create a new vector with values equal to 
% vec if they are > than 0, and equal to 0 if they <= 0.

vec=[3 5 -2 5 -1 0]

%one method: loop through vec
new_vec=zeros(size(vec));        %initialize to zeros
for i=1:size(vec,2)
   if vec(i)>0 new_vec(i)=vec(i); end
end
new_vec

% But often loops can be avoided by using built in matlab functions
new_vec2=zeros(size(vec));
tmp=find(vec>0)       %gives indices of all values of vector that are not 0
new_vec2(tmp)=vec(tmp)

%(6) Creating functions using m-files:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Functions in matlab are written in m-files. OPEN AN M-FILE called 
% "thres.m" In the m-file put the following: 

function res=thres(inp)

res=zeros(size(inp));
tmp=find(inp>0)       %gives indices of all values of vector that are not 0
res(tmp)=inp(tmp)

% note: we have literally copied the code we wrote earlier into the file.
% For readability, we used more general names for the variables.
% res is the value the function returns, and inp is the parameter
% passed to the function. You can use any names you like for the
% return value and parameters...

% from the command line: we can call thres with any matrix or vector
thres(vec)
thres([-5 5 5; 4 5 -1])


%(7) Plotting graphs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% of vectors:
x=[0 1 2 3 4];
plot(x);
plot(x,2*x);
axis([0 8 0 8])

x=pi*[-24:24]/24;
plot(sin(x));
plot(x,sin(x));
xlabel('radians');
ylabel('sin value');
title('dummy');
gtext('put cursor where you want text and press mouse');

% several graphs in one plot:
figure               %get new figure
subplot(1,2,1);
plot(x,sin(x));
subplot(1,2,2);
plot(x,2.*cos(x));

figure(1)
clf
plot(x,sin(x));
hold on              %use hold off to release hold           
plot(x,2.*cos(x),'--');
legend('sin', 'cos');

% using semilog
figure
x=-5:.25:5;
subplot(1,2,1)
plot(x,exp(x));
subplot(1,2,2)
semilogy(x,exp(x))

% matrices 
figure
m=rand(8,5);
showIm(m)
m=round(m);
showIm(m)
figure
imagesc(m)
colormap('gray');

