% =====================================
% MAE_82 Discussion Session
% Instructor: Prof. Rosen
% COPYRIGHT by Bionics Lab, UCLA
% 2016 Script
% =====================================

% This is a reading tutorial, you can copy my codes to another scripts and run.

% Outline:
% (1) Introduction to Matlab Desktop
% (2) Arrays and Matrices
% (3) Linear Algebra
% (4) Script Writing
% (5) Plot

%% (1) Matlab Desktop 
%     Current Folder: 
%     Only files within current folder can be accessed, to use a file in a
%     different folder, copy that file into Current Folder, or add path to your Current Folder.
%
%     Command  Window:
%     Input command and check output. Use "clc" command to clear.
%
%     Workspace:
%     Data created by command or scripts, can be saved or imported. Use
%     "clear" command to clear. (Unsaved data will be lost)
%     


%     Example01: Create and use variables
      a=2;
      b=3;
      c=a+b;
      d=exp(sqrt(c));

%     Note: command window will not output variables with semicolon ";", use
%           workspace to check variable value.
%

%     Use help command for more options   
%     Ex) help exp
%% (2) Arrays and Matrices

%     Example02: Create an array
      arr=[1 2 3 4];
      arr=1:1:4;
      % start:step:end, when omit step, by default the step is set as 1
      % The middle argument doesn't have to be a positive integer, for
      % instance, 4:-1:1 will return an array [4 3 2 1], and 1:0.5:2 will
      % return an array [1 1.5 2]

%     Example03: Create a matrix
      mat=[1 2 3;4 5 6;7 8 9];
      % Only rectangular matrices can be defined in Matlab, expression like
      % mat=[1 2 3;4] is illegal

%     Example04: Create special matrices
      ZeroMatrix=zeros(3,6); % Generate a zero matrix
      OneMatrix=ones(4,2); % Generate a matrix with one for all elements
      IdentityMatrix=eye(5); % Generate an identical matrix
      RandomMatrix=rand(3,3); % Generate a random matrix

%     Example05: Matrix Operations
      A=[2 5 3;8 1 2;0 4 6];
      B=[1 5 5;2 8 1;5 0 7];
      
      A+10 % Add 10 to every elements
      sin(A) % for each element
      
      A' % transpose of A
      inv(A) % inverse of A
      AA=[A A]
      BB=[B;B]
      element=A(2,3) % Find element (2,3) in matrix A
 
      
      Second_Row_of_A=A(2,1:3)
      % "m:n" means "from number m to number n", if omit both m and n,
      % means "the whole dimension", i.e. you can also write:
      Second_Row_of_A=A(2,:) % Same as above command
      
      sum(B,1) % or sum(B), summation of each column, returning a row vector
      sum(B,2) % summation of each row, returning a column vector

%% (3) Linear Algebra
      A=[2 4 1;7 4 6;5 3 0];
      B=[5 1 3;2 9 8;4 7 1];
      C=[3;5;1];

%
%
%     Operators:
%     +      addition
%     -      subtraction
%     *      Multiplication
%     /      Division
%     \      Left Division
%     ^      Power
%     '      Complex Conjugate Transpose
%     ()     Specify Evaluation Order
%     .*     Element-by-element Multiplication
%     ./     Element-by-element Division
%     .\     Element-by-element Left Division
%     .^     Element-by-element Power
%
%     You should pay extra attention to element-by-element operators,for
%     example
%     x=[1 2 3 4]
%     If you want x^2 for each element, simply input x^2 will lead to an
%     error because matlab would consider x as an row vector, thus x^2 will
%     be illegal. The correct way to do that is x.^2


%     Matrix Addition and Subtraction
%     Example06: 
      A+B
      A-B
      % marices must be in the same size, the following example will lead to an
      % dimension mismatch error:
      % A+C

      
%     Matrix Multiplication
%     Example07: 
      A*C
      % multiplications must satisfy the dimension compatibility
      % conditions, following example will lead to an dimension mismatch
      % error:
      % C*B
      %
      % Exception: 1*1 matrix is usually regarded as a scalar
      
%     
%     Inverse and Determinants
%     Example08: 
      det(A)
      inv(A)
 
%% (4) Script Writing
%     Conditional Control
%     i. if...else...
%     Example09:
      a=randi(100,1) % Generate a random integer from 1 to 100
      if a<50
          disp('a is less than 50') % a < 50
      elseif a<80
          disp('a is between 50 and 80') % 50 < a < 80
      else
          disp('a is equal or larger than 80') % 80 < a
      end

%     Loop Control
%     i. for-loop
%     Example10:
      a=zeros(5,1); % define a zero vector
      for i=1:5
          a(i)=rand; % give a random value to each element
      end

      % Note that it is always a good habbit to define a zero matrix before
      % you operate on the elements, you can also run this for loop without
      % 'a=zeros(5,1)' but that will result in slowness and uncertainty of
      % the program
      

%     ii. while-loop

%     Example11:
      a=zeros(5,1); % define a zero vector
      i=1; % set the pointer
      while i<6 % iterte whenever i<6
          a(i)=i;
          i=i+1; % move the pointer to the next element
      end
      % while-loop may be more capable of iteration when the number of
      % iteration is unknown. However you can also use for-loop to
      % achieve the function of a while-loop by modifying 'i', and vice
      % versa

%% (5) Plots
%     Example12: Plot sin(t) from 0 to 10 seconds
      t=0:0.1:10;
      x=sin(t);
      F1 = figure(1);
      plot(t,x) %t and x should have same size
      set(F1,'Position', [200 500 500 400]); % [ Left_bottom_corner_horizontal_position Left_bottom_corner_Vertical_position Width Height ]
      axis([0 10 -1.2 1.2]) % axis([xmin xmax ymin ymax])
      xlabel('t','FontSize',14)
      ylabel('sin(t)','FontSize',14)
      title('sin plot','FontSize',14)
      set(gca,'FontSize',14) % Axis fontsize
      grid on % Drawing grid on graph
      

%     Example13-1: Plot sin(t) and 0.3*cos(t*1.5) on the same plot
%     1st method
      figure(2)
      t=0:0.1:10;
      x1=sin(t);
      x2=0.3*cos(t*1.5);
      plot(t,x1,'r--',t,x2,'b.') % use '' to specifiy the color / shape / marker of the curve
      %     Use command "help plot" for color, shape and marker options
      legend('x1','x2')
      axis([-1 11 -1.2 1.2]) % axis([xmin xmax ymin ymax])
      grid on
      
%     Example13-2: Plot sin(t) and 0.3*cos(t*1.5) on the same plot
%     2nd method
      figure(3)
      t=0:0.1:10;
      x1=sin(t);
      x2=0.3*cos(t*1.5);
      plot(t,x1,'r--') % use '' to specifiy the color / shape / marker of the curve
      hold on
      plot(t,x2,'b.') % By using hold on, you can draw other graph on previous plot.
      legend('x1','x2')
      axis([-1 11 -1.2 1.2]) % axis([xmin xmax ymin ymax])
      grid on
      hold off
%     
%
%     Example14: Display 2 plots in the same window
      figure(4)
      t=0:0.1:10;
      x1=sin(t);
      x2=0.3*cos(t*1.5);
      subplot(2,1,1); % subplot(number of rows, number of columns, currently activated plot), the number of plot is counted starting from the first row
      plot(t,x1,'b')
      subplot(2,1,2);
      plot(t,x2,'r')

%     Example15: 3D-Plot
      figure(5)
      [X, Y]=meshgrid(-2:.2:2); % Generate a 2D mesh grid
      Z= X.* exp(-X.^2-Y.^2); % z=x*exp(-x^2-y^2)
      surf(X,Y,Z) % create a surface plot
      
%     How to save graph?
%     You can find save button among the buttons in graph.
%% Reference
%  MATLAB Primer, The MathWorks, Inc, Version 2015b
