%  a matlab demonstaration by Carl de Boor to Ron's CS412, spring 99.
$  highly recommended!
%  this is a cleaned-up and heavily edited diary of the 04feb99 session of
%  CS412. It is worthwhile reading through, particularly in order to catch
%  the changes, particularly the Vandermonde example ...

>> % Matlab's characteristics: interactive (hence interpretative),
               matrix and vector arithmetic,
               handy graphics, extensible + adaptible, relying strongly on
               default values for easy work.
                            
>> % online information comes in many forms. Try them all!
>> tour % nontechnical overviews
>> demos % try the first few matlab demos, about basic stuff
>> helpdesk % even gets you the official (typeset) manuals
>> helpwin % this is the quick way; it gets you a second window showing
           % groups of commands, lets you click on groups and on specific
           % commands
>> help mean  % gives information about a specific command
>> 
 MEAN   Average or mean value.
    For vectors, MEAN(X) is the mean value of the elements in X. For
    matrices, MEAN(X) is a row vector containing the mean value of
    each column.  For N-D arrays, MEAN(X) is the mean value of the
    elements along the first non-singleton dimension of X.
 
    MEAN(X,DIM) takes the mean along the dimension DIM of X. 
 
    Example: If X = [0 1 2
                     3 4 5]
 
    then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1
                                                      4]
 
    See also MEDIAN, STD, MIN, MAX, COV.

%  Basic objects:  m-by-n matrices 
%  vectors: m-by-1  or  1-by-n  (ambiguity can be troublesome at times)
%  scalars: 1-by-1

%  entries can be scalars (numbers) or characters (giving rise to strings).

%  INTERACTIVE: gives back results unless semicolon is used:
>> a = [1 2 3]
   a =
   
     1     2     3
   
>> a = [1 2 3];
>> % many ready-made matrices:
>> zeros(3)
   ans =
     0     0     0
     0     0     0
     0     0     0

>> ones(2,3)
   ans =
     1     1     1
     1     1     1
   
>> eye(2)
   ans =
     1     0
     0     1
   
>> rand(2,3)
   ans =
    0.9501    0.6068    0.8913
    0.2311    0.4860    0.7621
   
>> 0:4
   ans = 0     1     2     3     4
   
>> 4:-1:0
   ans = 4     3     2     1     0
   
>> x = linspace(0,2*pi,21)
   x =
  Columns 1 through 7 
         0    0.3142    0.6283    0.9425    1.2566    1.5708    1.8850
   
  Columns 8 through 14 
    2.1991    2.5133    2.8274    3.1416    3.4558    3.7699    4.0841
   
  Columns 15 through 21 
    4.3982    4.7124    5.0265    5.3407    5.6549    5.9690    6.2832
   
>> x(11)
   ans = 3.1416
>> % is that really pi??? Use more explicit format:
>> format long
>> x(11)
   ans = 3.14159265358979

% If you really want to know what's in the machine, use hexadecimals:

>> format hex
>> x(11)
   ans = 400921fb54442d18
>> % not so easy to read :-) even when you use a familiar number:
>> 1
   ans = 3ff0000000000000
% fortunately, you don't usually have to worry about how numbers are
% actually represented.
>> format short
% many other ready-made matrices, e.g.:
>> magic(4)
   ans =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
   
>> % MAKE YOUR OWN matrices, using brackets:
>> A = [1 2 3; 2 4 6]
   A =
     1     2     3
     2     4     6
>> % Note use of semicolon to separate rows. Could also do
>> A = [1 2 3
       2 4 6]
   A =
     1     2     3
     2     4     6
   
>> b = [4;2]
   b = 
     4
     2

% can even put together matrices to make bigger matrices:
>> C = [b A]
   C =
     4     1     2     3
     2     2     4     6
   
>> D = [ A b;b' 1 -1]
   D =
     1     2     3     4
     2     4     6     2
     4     2     1    -1
>>  % the empty matrix:
>> []
   ans = []
>> % If you want to know more about a variable, use  whos
>> whos ans
  Name      Size         Bytes  Class

  ans       0x0              0  double array
   Grand total is 0 elements using 0 bytes
   
>> % Note that  ans  is the default variable
% you can ask other questions:
>> why
   Damian wanted it.
>> why
   A system manager wanted it that way.
>> why
   The tall and bald bald mathematician told me to.

>> % ARITHMETIC OPERATIONS come in two flavors: 
>> % MATRIX, e.g.,
>> b'*A
   
   ans = 8    16    24

>> % POINTWISE,  e.g.,
>> A.*A
   
   ans =
     1     4     9
     4    16    36

>> % basic ops: +, -, *, /, ^,  \
%  note the  backslash:  A\B tries to give you  X  such that  A*X = B
%  very handy for solving a system of linear equations, data fitting, etc. 

%  PLOTTING
>> plot(A)  % matlab tries to make sense of this input; given a matrix, it
            % plots all its columns, each as a sequence of values at integer
            % points, using straight line connects as the default, and
            % different default colors for different columns
>> %  here is  A  again, to compare against the picture:
>> A
   A  =
     1     2     3
     2     4     6
%  Here is a more standard plot, using the point sequence x we generated
%  earlier:
>> plot(x,sin(x))

%  We can become ever more specific about the plot details:
>> plot(x,sin(x),'-or')
>> plot(x,sin(x),'-or','linewidth',2)
>> title('plot of sine on [0,2pi]')
>> xlabel('note the use of line-fill AND a marker')

>> % many other plotting commands: mesh, surf, contour, etc..
>> % question from class: how about plotting just some data points?

>> % For fun, here is a way of getting some points interactively:
>> [x,y] = ginput
>> % (I had trouble with this, eventually realizing that, when finished,
   %  I must hit <RETURN> while the cursor is in the figure window.)

   x =
    0.7097
    0.6106
    0.4286
    0.2304
    0.2166
   y =
    0.8655
    0.3070
    0.2602
    0.3947
    0.7281

>> plot(x,y,'kx')
% question from class: 
     % can I label those points, e.g., with their coordinates?
>> help text
 TEXT   Text annotation.
    TEXT(X,Y,'string') adds the text in the quotes to location (X,Y)
    on the current axes, where (X,Y) is in units from the current
    plot. If X and Y are vectors, TEXT writes the text at all locations
    given. If 'string' is an array the same number of rows as the
    length of X and Y, TEXT marks each point with the corresponding row
    of the 'string' array.

    etc
 
>> text(x(1),y(1),sprintf('(%g, %g)',x(1),y(1)))

% question from class: can I put a curve through those data?

>> s = spline(x,y);

>> hold on
>> xx = linspace(min(x),max(x),51);
>> plot(xx, ppval(s,xx))

% matlab commands come in many different ways. One way to classify them is:
%
% SCALAR commands, like  abs  or sin that expect a scalar as input and return
       % a scalar as output. When applied to a vector or matrix, they return
       % the vector or matrix obtained by applying the command to each entry.

>> sin(x)
   ans = 
    0.6516
    0.5734
    0.4156
    0.2284
    0.2149
  
% VECTOR commands, like  min, max, sum, prod, cumsum, cumprod, sort, diff 
      % that act on vectors and return a scalar or a vector. When applied to
      % a matrix, they work on each of that matrix' columns (unless told
      % otherwise by an additional input argument).
>> min(A) 
   ans =  1  2  3
>> min(A,[],2)
   ans = 
         1
         2
% (the empty matrix here is a kludge; the first version of the min command 
% allowed the version min(A,B) which applies  min  pointwise, i.e., returns
% the matrix of the same size as A and B whose i,j entry is the smaller of
% A(i,j) and B(i,j). In particular, the command
>> min(A,2)
   ans = 
     1  2  2
     2  2  2

>> % since, by another nice default: If matlab expects a matrix of a certain
size and is given a scalar instead, it simply makes up the matrix of that
expected size all of whose entries equal that scalar. )

>> cumprod(1:4)
   ans = 1     2     6    24
>> 

% MATRIX commands, like  eig  or  norm , operate on matrices .

%  matlab commands are built-in or M-files. Tell the difference by trying to
% print them on the screen using  type:

>> type min
   min is a built-in function.
>> type mean
   
   function y = mean(x,dim)
   %MEAN   Average or mean value.
   %   For vectors, MEAN(X) is the mean value of the elements in X. For
   %   matrices, MEAN(X) is a row vector containing the mean value of
   %   each column.  For N-D arrays, MEAN(X) is the mean value of the
   %   elements along the first non-singleton dimension of X.
   %
   %   MEAN(X,DIM) takes the mean along the dimension DIM of X. 
   %
   %   Example: If X = [0 1 2
   %                    3 4 5]
   %
   %   then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1
   %                                                     4]
   %
   %   See also MEDIAN, STD, MIN, MAX, COV.
   
   %   Copyright (c) 1984-98 by The MathWorks, Inc.
   %   $Revision: 5.13 $  $Date: 1997/11/21 23:23:55 $
   
   if nargin==1, 
  % Determine which dimension SUM will use
  dim = min(find(size(x)~=1));
  if isempty(dim), dim = 1; end
   
  y = sum(x)/size(x,dim);
   else
  y = sum(x,dim)/size(x,dim);
   end

% M-files come in two flavors: scripts and functions.

% SCRIPTS are just abbreviations; calling on a script (by typing its name
% on a single line) has exactly the same effect as typing in all the lines 
% of the script one by one.

% FUNCTIONS are essentially different in that they start their own work
% space. This is very convenient since the author doesn't have to worry about
% what variables are already in the workspace. It does mean that the function
% needs to be given input and (usually) the only thing one knows about its
% activities is via the output it provides.

% The function mean printed above is a typical example; it has two input
% arguments, and (only) one output argument. Note that all its assignment
% statements end in a semicolon since there's no use having those intermediate
% results printed out.

% Note the initial block of comments (identified by the percent sign). This
% block is printed on the screen in response to the help command:
>> help min

 MIN    Smallest component.
    For vectors, MIN(X) is the smallest element in X. For matrices,
    MIN(X) is a row vector containing the minimum element from each
    column. For N-D arrays, MIN(X) operates along the first
    non-singleton dimension.
 
    [Y,I] = MIN(X) returns the indices of the minimum values in vector I.
    If the values along the first non-singleton dimension contain more
    than one minimal element, the index of the first one is returned.
 
    MIN(X,Y) returns an array the same size as X and Y with the
    smallest elements taken from X or Y. Either one can be a scalar.
 
    [Y,I] = MIN(X,[],DIM) operates along the dimension DIM.
 
    When complex, the magnitude MIN(ABS(X)) is used. NaN's are ignored
    when computing the minimum.
 
    Example: If X = [2 8 4   then min(X,[],1) is [2 3 4],
                     7 3 9]
 
        min(X,[],2) is [2    and min(X,5) is [2 5 4
                        3],                   5 3 5].
 
    See also MAX, MEDIAN, MEAN, SORT.

>> the functions you write all should start with such a help block.

%  WORKSPACE: To find out the content of the current workspace, use  who:
>> who

   Your variables are:
   
   A         D         ans       s         y         
   C         a         b         x         
   
>> % ... i.e., all the variables we've introduced earlier. For more detail
>> % use  whos:
>> whos x
  Name      Size         Bytes  Class
   
  x         5x1             40  double array

   Grand total is 5 elements using 40 bytes

>> % INLINE functions: there is an additional way to construct a function
           % helpful for quick experimentations:
>> f = inline('3*x - 4')
   f =
   
     Inline function:
     f(x) = 3*x - 4
   
>> % You use it just like the built-in functions:
>> f(4/3)
   ans = 0
>> % If you want them to work entrywise on matrices, you have to vectorize
them:
>> f = vectorize(f)

f =
     Inline function:
     f(x) = 3.*x-4

% You can make up your own commands, by putting appropriate function M-files
% into the current directory or into a directory in the matlab search path.
% When matlab comes across a name, it checks for it: 
% first in the workspace,
% then among the built-in functions,
% then in the current directory, 
% then in the directories in the matlab search path.

>> % language constructs: for, while, if-else, switch-case, etc.
>> % for a=b, ..., end  
>> for j = eye(3)
  j'
>> end

   ans = 1     0     0
   
   ans = 0     1     0
   
   ans = 0     0     1

>> while 1
  disp('I must go on'), pause(1)
>> end
   I must go on
   I must go on
   I must go on
     etc
% to TERMINATE a run-away calculation, use  CONTROL-c .

>> % if condition, ...., else, ..., end

>> % condition needs relational operators: ==, ~=, <, etc, &, |, ~, all, any


>> % MAKING NEW MATRICES FROM OLD
>>  %  repmat

>> x = 1:3;
>> repmat(x,2,3)
   
   ans =
     1     2     3     1     2     3     1     2     3
     1     2     3     1     2     3     1     2     3

>> %  A(b,c)  gives the matrix whose (i.j) entry is  A(b(i),c(j)):
>> A
   A =
     1     2     3
     2     4     6
   
>> A(:,2:3)
>> ans =
     2     3
     4     6

>> A([1 1],[3 1 1])
   ans =
     3     1     1
     3     1     1
>> % Note the use of  :  to indicate that ALL rows are to be taken.
>> 
>> % reshape(A,m,n)
>> reshape(A,3,2)
   ans =
     1     4
     2     3
     2     6

% question from class: how can I print out the diary, right from matlab?

% Close the diary, by saying   

>> diary off

% then, assuming you are on a unix machine, you could use the standard system
% command  lpr  (that prints to the default printer), as long as you remember
% the name of the file (feb04  in our case)

>> !lpr feb04

>> % NOTE the use of the exclamation point to tell matlab that this is a
   % system command.

% If you want to edit it first, you could, in this way, evoke your favorite
% editor to work on the diary file.

% If you'd rather do it later, be sure to remember the directory in which the
% file resides. Use to pwd command to help you:
>> pwd

ans = \matlab\work

>> ls

feb04


%  I ran out of time before I could do the following Vandermonde example:

use vector and matrix operations, for efficiency (avoiding for-loops since
matlab is interpretive).
Example: generate the Vandermonde matrix V(i,j) = t(i)^(j-1), i=1:n; j=1:k:

for i=1:n
   for j=1:k
      V(i,j) = t(i)^(j-1);
   end
end

Several complaints:
(i) many copies of increasingly larger matrices V are generated;
response: start with a V of the right size:

V = ones(n,k);  % first column is already correct!

(ii) if I know  t(i)^(j-1), then get t(i)^j from it just by multiplying by t(i)

for i=1:n
   for j=2:k
      V(i,j) = V(i,j-1)*t(i);
   end
end

(iii) since Matlab is interpretive, avoid loops by using vector and matrix
operations:

inner loop can be replaced by
for i=1:n
   V(i,:) = t(i).^(0:k-1);
end

which is quite expensive, or by

for i=1:n
   V(i,:) = cumprod([1,repmat(t(i),1,k-1)]);
end

or can replace outer loop by
for j=2:k
   V(:,j) = V(:,j-1).*t(:);
end

or can replace both loops by

V = repmat(t(:),1,k).^repmat(0:k-1,n,1);

(which is quite expensive), or by

V = cumprod( [ones(n,1) repmat(t(:),1,k-1)], 2);

which is much faster, but may be hard to understand..






