%% Lecture 1, ACM 11
%% When to use MATLAB
%{ 

These notes will be posted on the class website

First topic: which language to use, and when

MATLAB excels at Numerical Computation.  It is also easy to use, and is a
very high-level language (for example, you can multiply two matrices
with a single command).

MATLAB competes with many languages, including:
    - Mathematica, Maple and other Sybolic math packages
    - MATLAB imitations (FreeMat, Octave, SciLab, xmath) and 
        IDL, mathCad, etc.
    - C and Fortran   [staples of the high-performance community]
    - C++, as well as C# etc.   [modern Object-Oriented languages]
    - java and python   [also modern Object-Oriented languages]
    - perl, bash and other shells   [mainly data manipulation]
    - Microsoft Excel   [data manipulation, plotting]
    - S and R   [statistics languages]

When to use MATLAB?
    (1) if you can afford to buy it, or can get it free
    (2)(a) for numerically intensive computations, or...
    (2)(b) for plotting and dealing with data
    (3) for faster DEVELOPMENT than C and Fortran
    (4) for faster EXECUTION than most other languages

When NOT to use MATLAB?
    (1) for symbolic math, if you have access to Mathematica or Maple
    (2) you want free software, or want to release code that doesn't
            require the user to have MATLAB
    (3) you are doing something SERIOUS, like climate modelling,
            solving 3D Partial Differential Equations, etc.

Most languages can do everything, even if they are not the best at it.
Here are some compelling reasons to use MATLAB:

    (1) the language is rather fast to learn, and many functions are
            already builtin
    (2) the HELP menu is fantastic
    (3) MATLAB deals with sparse matrices very well
    (4) the debugger and profiler are powerful and easy to use
    (5) MATLAB is an industry standard, much like Microsoft Word, or
            autocad.  This also means that the web is full of
            MATLAB resources.

MATLAB is not a compiled language.  It is also much more than
a language, since it provides many graphical tools as well
as extended functionality with toolboxes.
%}

%% Getting started
%{
    Basics: development environment
        - command prompt (note: MATLAB can be run from the terminal, 
                more on this later)
            You can use tab-completion, and use the up-arrows.
            Drag-n-drop also works.
        - m-file editor (note: you can use your own editor too)
        - Command History window
        - Workspace
            - for plotting, and Variable Editor
        - Current Directory, and file browser
        - Menus, and links to the Help Menu
        - when you plot a figure, the Figure menus are also available
                (more on plotting later)
    All of these windows can be re-arranged

    What is this file?
        This is an example of a "m-file".  The file is saved as "lecture1.m"
        MATLAB also automatically makes backup files, called either "lecture1.asv"
        (windows) or "lecture1.m~" (unix/linux); this behavior can be changed.

        m-files contain sequences of commands that are executed in order.
        It is very similar to using the command line, but much more convenient
        
    Two important concepts:
        (1) Comments.  Everything written here is a comment.  There are two ways to 
                write comments: either comment a single line with "%", or 
                use block comments to comment several lines, using "%{"
                followedd by "%}".  See this file for examples.  Note that you 
                cannot have ANYTHING on the line that starts with "%{".
                By default, the editor puts comments in green (you can change this).
                For printing an m-file, you can make the comments appear in italics; 
                please do this for your homework!  See the "page setup" menu.

        (2) Cells.  MATLAB has two meanings for the word "cell", so don't get 
                confused.  The first meaning of "cell" is used in a m-file, and
                it is a way to split the m-file into chunks, each of which
                can be executed separately.  This is a very useful tool.
                To execute a single cell, see the button in the toolbar, or
                hold down "ctrl" and then hit "enter" on your keyboard.
                The beginning of a cell is a special comment line that
                begins with two "%", not just one.
                The other use of the word "cell" refers to a type of variable, and
                will be discussed later.
    Other basics
        The editor is highly customizable, and it has many keyboard shortcuts
            (most shortcuts are either the same as Emacs, or as basic Windows 
            shortcuts).  These can be customized as well.
        For your system, you should know the following shortcuts:
            (1) saving the file 
                (e.g. ctrl+X, ctrl+S for unix, or cntr+S for windows)
            (2) commenting a line of code
                (e.g. ctrl+/ for unix, ctrl+R for windows)
            (3) uncommenting a line of code 
                (e.g. ctrl+T for unix and windows)
        see the "Text" menu for more (e.g. changing the indent: ctrl+I)
%}
%% 
% Before we start, a brief check of the version number
% The requirements for this class are version 7.2 (R2006a) or later
% Please see instructor or TA with installation questions.  Remember, for
% Windows Vista, run everything as Administrator.  MATLAB is also on all
% Windows library computers, as well as on the ugcs cluster and the its
% machines.  You can run MATLAB remotely as well.
clc
version
license('test','statistics_toolbox')
clear
% in MATLAB, like many languages, "1" means true and "0" means false
% and you can also use the keyword "true" (without quotes) to make
% your code more readable.  For a general number n, n is considered "false"
% if it is zero; any other value is "true".
%% Basics: using MATLAB as a calculator  (this is an example of a cell)
%  (aka: why you will never use your TI-89 again)
clc         % this clears the screen of old output
3 + 5
%%
clc
3 + 5;              % the semicolon suppresses output ( THIS IS A COMMENT)
3+             5;   % MATLAB ignores whitespaces usually
                    % (though sometimes it treats them as a comma)
% Note: comments can start ANYWHERE in a line of code
%   but you cannot "undo" a comment on the same line, e.g. % comment % code
%% using a simple variable
x = 4
% Note: we do not need to "declare" x, as we would in C or Fortran
% MATLAB is case-sensitive, so if we as for the value of "X", we'll
% get an error.
% For naming your own variables, you can use any mixture of upper- and 
% lower-case.  Variables may not start with a number, but can have
% numbers elsewhere in the name.
%%
x = 8; 2*x  % the semicolon suppresses output AND allows us
            % to add a second command.
%%
clc
exp(i*pi)   % "i" and "j" are both sqrt(-1)
%%
i = 5;
exp(i*pi)
%%
clear i     % erases "i" from the workspace; it will now be sqrt(-1) again
% Note: to clear more than one variable, do NOT separate the variable
% names with a comma -- just uses spaces, e.g.
% >> clear i j
%%
clc
x = exp( sin( atan( abs( log( 3 ) ) ) ) );
disp(x)
% order of operations: don't memorize this, just use parenthesis
% simplest commands: * (multiplication), + (addition), - (subtraction),
%   / (divistion), ^ (exponentiation)
%% vectors and matrices
clc; x = [ 1 2 3; 4, 5, 6]
%   the spaces and commas separate columns
%   and the semicolons separate rows
%%
% various ways to make a matrix
x = [ 1 2 3
    5 4 6]
%   in this case, the second line indicates a new row

%% precautions about matrices
% some operations are "matrix" operations, and others
% are "component-wise" aka "element-wise"

% x * x       % this tries to do matrix multiplication
%%
x .* x      % this works element-wise
%%
x = [1 2; 3 4];
exp(x)      % this is element-wise
expm(x)     % this is an inherent matrix operation
%% 
x ^ 2       % this is matrix multiplication, e.g. "x * x"
x .^ 2      % this is element-wise, e.g. "x .* x"


%% Strings, and such; use single quotes always! 
% Strings are matrices of characters; each character is represented
% by an integer (most common characters are represented by ASCII code,
% with an integer between 0 and 127)
clc; s = ' I am a ''string'
%%
s + 0       % automatic conversion to ASCII code ("double(s)" does the same)
%%
double('a string')
%%
% double( a string )      % this fails
%%
char( s + 0 )   % convert back to characters
char( s + 'A' - 'a' )


%% Breaking up long-lines of code onto two lines
s2 = ['This is a long, boring, and seemingly pointless string that is' ...
    ' in fact so long, it must be written on two lines'];
disp(s2)


%% very simple plotting
clc; ezplot( 'sin' )  % default domain is -2*pi to 2*pi
%% 
ezplot( 'cos(5*x)' )    % this time, MATLAB guesses that "x" is the variable


%% using the HELP menu
help ezplot
%{
    conventions:
        MATLAB functions are always lowercase.  But, just to mess
        with you, the Help files always write them in all uppercase.
        Don't fall for it!
%}
%%
% if you don't know the name, here's a primitive way to search
% >> lookfor plot
%% and finally, the powerful Help Browser: either hit "F1" key, or...
doc ezplot
%{
    convention:
        when using a command like "doc", there are three ways to call it
        (1) doc ezplot
        (2) doc 'ezplot'
        (3) doc('ezplot')
    but the followig will NOT work
        (4) doc(ezplot)
    because MATLAB thinks the argument is a variable
        for more details, see >> help syntax
%}
%% "help" also works on directories
%{
% here is a list of very useful categories/directories
help ops        % lists the basic operations, very useful for beginners
help elfun      % lists things like cosine, exp, log, etc.
help elmat      % basic matrix stuff
help datafun    % min, max, convolution, fft, etc.
help demos      % a list of demos
help general    % workspace, path, saving/loading files, ...
help graph2d    % plotting
help helptools  % a list of the HELP functions
help lang       % control flow (if, for, ...), errors,
help strfun     % dealing with strings

% =====  some other useful, but slightly more advanced categories
help datatypes  % stuff about characters, strings, integers, etc.
help codetools  % editing, debugging, profiling, openvar, pathtool, publish
help funfun     % functions acting on functions, 
                %   e.g. minimization, integration, ODEs
help graphing   % more powerful 2- and 3-D plotting tools
  % see also >> help plottools
  % and      >> help scribe
help graph3d    % 3D graphics
help matfun     % useful, powerful matrix utilities, e.g. 
                %   finding eigenvalues, solving linear equations
help polyfun    % polynomial tools, e.g. finding roots, interpolation
help sparfun    % tools for sparse matrices
help specgraph  % special graphics: pie charts, countour plots,
                %   movies, images
help timefun    % time functions: date, clock, timing an operation (tic, toc)

% =====  and less useful or more obscure categories
help iofun      % for using zip, loading Excel files, downloading webpages,
                % sending email, basic reading/writing of files,
                % controlling a serial port, ...
help specfun    % special functions (e.g. Bessel functions), dot product, 
                % number theory (primes, factor, factorial, nchoosek)
help audiovideo % controlling the speakers, playing video...
help guide      % for designing GUI's; see also >> help uitools
help mcc        % the MATLAB compiler, more on this later if we have time
help winfun     % Windows specific stuff, e.g. winopen
%}
%% More sources of help
%{
    The internet has about 10,000 MATLAB tutorials.  Unfortunately,
    I don't have any particular ones to recommend.  If I missed some
    basic syntax stuff, the Wikipedia page on MATLAB probably has it.

    Books: Cleve Moler (founder of MATLAB) has a book online for free.
        Also, I've reviewed about a dozen current MATLAB books.
        See the website for links and titles.
%}

%% More on matrices and vectors
% An easy way to generate a simple vector:
clc; x = 1:8
% x = linspace(1,8, 8)      % does the same thing
%%
% Transpose:
x'
%%
% or 
x.'
% What's the difference?  x' is actually the complex conjugate transpose,
% aka the adjoint.  If you just want to "flip" a matrix, use "x.'"
% If x has all real numbers, they are of course the same.
%%
% Indices: use ( ) to access an element, not [ ]
% For creating a matrix, use [ ] not ( ).  
clc; x = [ 1 2; 3 4; 5 6]
x(2,1)      % convention is x(row, column)
%%
% We can also use "linear indices", with "column-major" order (like 
% FORTRAN, unlike C and most other languages).
% Major note: MATLAB is 1-indexed, unlike C.
x(2)
x(5)
% to convert from subscripts (e.g. x(2,1) ) to linear indices (e.g. x(2) ),
% MATLAB has the functions "ind2sub" and "sub2ind"
%%
% More powerfully, we can index many entries at once, using either
% subscripts or linear indices.  Here, we use the ":" operator.  There are
% several equivalent syntaxes
x(1:3, 1)       % shows just the first column ( x(1:3,2) is 2nd column )
x( :,  1)       % exact same
x(1:end, 1)     % exact same; the special keyword "end" refers to the last
                % entry
% This kind of referencing is sometimes called "slicing"
% Note that the conventions are different that Python's slices
%%
clc; x
x( 3:5 )        % note that this "flattens" the matrix into a vector
%%
clc; x
x( 1:2:5 )      % the "2" means that we go from 1 to 5 in increments of 2
%%
1:3:12          
%%
clc; r = randn( 1, 8) % make a random matrix of size 1 x 8
n = length(r);
r(2:end)
%%
clc; R = randn( 3,7)
R( 2, 3:5 )

%% "for" loops
% "for" loops are easy in MATLAB, but the syntax is different than most
% other programming languages.
clc
v = (1:4).^3 ;    % a row vector
for i = v
    disp(['v(i) is: ', num2str( i ) ]);
end

%%
% make sure it is a row vector
% otherwise we get unexpected results
clc
for i = v'
    disp(['v(i) is: ', num2str( i(1) ) ]);
end
%%
% a more compact way to write a for loop
% (ex. time how long it takes to do 500 FFT's of length 1000)
tic; for i = 1:500, fft( ones(1000,1) ); end; toc

%% linear systems
% the backslash operator is also known as "mldivide" (this is useful
% if you want to see its "help" entry; see also "help slash")
clc
A = hadamard(8)
x = ones(8,1)
b = A*x;
xhat = A\b         % solves the equation A*x = b for x
% another way to solve:
xhat = linsolve(A,b)
