% This is a sample script file to demonstrate some features of Matlab.
% It does not do anything particularly useful.
%
% Most scripts and functions will have a semicolon ";" at the end of every
% line so that the output will not appear in the terminal window.  Note that
% statements which begin and end compound statements (such as for, if,
% while, end, etc) do not produce output, so the semicolon is optional.  In
% this script, I omit the semicolon so that the output can be seen.
%
% Ian Mitchell for Matlab Tutorial, 9/12/07.

%-----------------------------------------------------------------------
% Create some simple arrays and matrices explicitly.

% Column vector.
a = [ 4; 99; 12 ]

% Row vector.  You really should use commas to separate columns, but you
% do not have to.
b2 = [ 55 - 22 12 ]
b3 = [ 55 -22 12 ]

% Array.  Need not be square.  Note that Matlab is case-sensitive, so
% we can have both variable "A" and variable "a" (although such variable
% naming is generally a bad idea).
A = [ 1, 2, 3, 4; 11, 12, 13, 14; 21, 22, 23, 24 ]

% Concatenation happens automatically, as long as the elements to be
% concatenated are the right shape.
A_beside_a = [ A, a ]
A_above_b2 = [ A; b2, b2 ]
A_beside_A = [ A, A ]

%-----------------------------------------------------------------------
% Create some matrices using special Matlab functions.

% Colon ":" used to create row vectors
colon_step_by_1 = 1:8;
colon_step_by_2 = 1:2:8;
colon_step_down = 8:-2:1;

% Get column vectors by transpose.
column_colon_step_by_2 = colon_step_by_2';

% All zeros.
all_zeros = zeros(4,3)

% All ones.
all_ones = ones(3,2)

% All fives.
all_fives = 5 * ones(3,2)

% The identity.
identity_4 = eye(4)

% Random matrices.
uniform_random_matrix = rand(5,5)
normal_random_matrix = randn(5,5)

% Diagonal matrices.
a_on_main_diagonal = diag(a, 0)
a_on_super_diagonal = diag(a, 1)

% Or get the diagonal.
diagonal_of_identity = diag(eye(4))

% Plus "+" is elementwise addition.
upper_bidiagonal = diag(a, 1) + eye(4)

% We can replicate matrices.
three_copies_of_a = repmat(a, 1, 3)

%-----------------------------------------------------------------------
% Indexing into arrays.  Remember: Rows then Columns.
bottom_right_element_of_A = A(3,4)

% Special index: "end".  Defined only inside "()" indexing into an array.
bottom_left_element_of_A = A(end,1)

% Use colon to pick out selected elements.
top_right_submatrix_of_A = A(1:2, 1:3)

% Another special case: Colon by itself specifies all indices in that
% coordinate.
bottom_two_rows_of_A = A(2:end, :)

% Any vectors can be used to index into arrays.
four_elements_of_A = A( [ 1 3 ], [ 2 4 ])

%-----------------------------------------------------------------------
% Other data types.  Matlab variables do not have to be declared before
% use.  The type of a Matlab variable is determined by the last
% assignment to it.

% We can have arrays of dimension higher than 2.  For historical reasons,
% arrays have dimension of 2 or more (ie vectors still have two dimensions).
% There is no square bracket notation to create them, but you can create
% them via the usual functions (zeros, ones, rand) and index into them in
% the obvious manner.
three_dim_array = rand(4, 3, 2)
subset_of_three_dim_array = three_dim_array(2, 1:3, 2)

% We can have strings.  They are treated as row vectors.
string1 = 'a string'
string2 = 'another string'

% We can have structures.
s.field1 = string1
s.field2 = 5

% We can have cell arrays, which are arrays in which each element can be any
% other data type (including another cell array).  It looks kind of like a
% pointer array, but remember that there are no pointers in Matlab.

% Cell arrays can be created by using {} instead of [].
cell1 = { 7, string1; s, a }

% Cell arrays can also be created by cell.
cell2 = cell(3,2)

% Cell arrays can be indexed by {}, in which case you get the desired
% element out of the cell array.  Multiple elements will be returned as a
% comma separated list -- useful in some circumstances, but what I would
% consider to be advanced Matlab syntax -- so you usually want to pick
% out just one element of a cell array.
bottom_right_cell_cell1 = cell1{2,end}

% Cell arrays can also be indexed by (), in which case you get a cell array.
% Usually, you don't want to do this.
bottom_right_element_cell1 = cell1(2,end)

% Cell arrays are particularly useful for storing collections of strings,
% since traditional arrays would require that each string be the same
% length.  For example, if you replace the {} with [] below, you will get an
% error.
cell_of_strings = { string1; string2 }

%-----------------------------------------------------------------------
% Operations on arrays.

% Multiply "*" and power (^) are the matrix versions.  
c = ones(4, 1)
A_times_c = A * c

square_A = A(1:3,1:3)
square_A_squared = square_A^2

% Divide "/" is an amazing function -- it can solve A * x = a, and so much
% more.  See "help slash" for details.
solve_for_x = square_A \ a
check_against_a = square_A * solve_for_x

% If you want elementwise, use ".*", "./" or ".^"
A_squared = A .* A
A_squared_again = A .^ 2

% Not the inverse of A!
inverse_of_elements_of_A = 1 ./ A

% Inverse of A (although you should in general use "/" instead)
inverse_of_square_A = inv(square_A)

% Most other Matlab functions perform elementwise.
sin_of_elements_of_A = sin(A)

%-----------------------------------------------------------------------
% Plotting.
figure
xs = linspace(0, 2*pi, 16)
ysin = sin(xs)
ycos = cos(xs)
h = plot(xs, ysin, 'b+-', xs, ycos, 'ro--')

% Label your plots.
xlabel('x');
ylabel('f(x)');
title('A simple example of Matlab plotting');
legend('f(x) = sin(x)', 'f(x) = cos(x)');

% You can also fiddle with line settings to make things prettier.
set(h, 'LineWidth', 2);

% Other commands you might consider investigating: figure, axis, subplot,
% semilogx, semilogy, surf, mesh, ...

%-----------------------------------------------------------------------
% Printing.  You can often print directly from Matlab these days, but you
% can also save your results to standard image file formats.
print -dpng 'trig.png';

% You can fiddle with the orientation and sizing either through menus, or
% with commands
orient tall
print -deps 'trig.eps';

% Other useful commands are setting the axis scale and/or grids.
orient landscape
axis equal
grid on
print -djpeg 'trig.jpg';

%-----------------------------------------------------------------------
% Finally, a brief example of why "vectorization" is good:
n = 5e6 + 1;
xs = linspace(0, 2*pi, n);
ys = zeros(size(xs)); 
tic
% You can put any line ending character after compound statement open or
% close that you like -- it does not make a difference.
for i = 1 : length(xs), 
  ys(i) = sin(xs(i)); 
end
toc

tic
ys = sin(xs);
toc

