SlideShare una empresa de Scribd logo
1 de 178
Descargar para leer sin conexión
Motivation
      How it is useful for:
                Summary




Introduction to MATLAB
          A Layman Approach


    P Bharani Chandra Kumar
     (bharani@aero.iitb.ac.in)

    Department of Electrical Engineering
       GMR Institute of Technology
               Rajam, AP


    Lecture series on MATLAB



P Bharani Chandra Kumar
Motivation
                     How it is useful for:
                               Summary




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation     History of MATLAB
                     How it is useful for:   Strengths of MATLAB
                               Summary       Weakness of MATLAB




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                    How it is useful for:   Strengths of MATLAB
                              Summary       Weakness of MATLAB




MATLAB stands for MATrix LABoratory.
    Developed primarily by Cleve Moler in the 1970s.
    Need student access to Fortran subroutines for solving
    linear (LINPACK) and eigenvalue (EISPACK) problems
    without requiring knowledge of Fortran .
    Developed as an interactive system to access LINPACK
    and EISPACK.
    Gained popularity primarily through word of mouth
    In the 1980s, MATLAB was rewritten in C with more
    functionality
    Mathworks, Inc. was created in 1984 is now responsible for
    development, sale, and support for MATLAB


              P Bharani Chandra Kumar
Motivation     History of MATLAB
                     How it is useful for:   Strengths of MATLAB
                               Summary       Weakness of MATLAB




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation     History of MATLAB
                 How it is useful for:   Strengths of MATLAB
                           Summary       Weakness of MATLAB




MATLAB is relatively easy to learn
MATLAB code is optimized to be relatively quick when
performing matrix operations
MATLAB may behave like a calculator or as a programming
language
MATLAB is interpreted, errors are easier to fix
Although primarily procedural, MATLAB does have some
object-oriented elements.




           P Bharani Chandra Kumar
Motivation     History of MATLAB
                 How it is useful for:   Strengths of MATLAB
                           Summary       Weakness of MATLAB




MATLAB is relatively easy to learn
MATLAB code is optimized to be relatively quick when
performing matrix operations
MATLAB may behave like a calculator or as a programming
language
MATLAB is interpreted, errors are easier to fix
Although primarily procedural, MATLAB does have some
object-oriented elements.




           P Bharani Chandra Kumar
Motivation     History of MATLAB
                 How it is useful for:   Strengths of MATLAB
                           Summary       Weakness of MATLAB




MATLAB is relatively easy to learn
MATLAB code is optimized to be relatively quick when
performing matrix operations
MATLAB may behave like a calculator or as a programming
language
MATLAB is interpreted, errors are easier to fix
Although primarily procedural, MATLAB does have some
object-oriented elements.




           P Bharani Chandra Kumar
Motivation     History of MATLAB
                 How it is useful for:   Strengths of MATLAB
                           Summary       Weakness of MATLAB




MATLAB is relatively easy to learn
MATLAB code is optimized to be relatively quick when
performing matrix operations
MATLAB may behave like a calculator or as a programming
language
MATLAB is interpreted, errors are easier to fix
Although primarily procedural, MATLAB does have some
object-oriented elements.




           P Bharani Chandra Kumar
Motivation     History of MATLAB
                 How it is useful for:   Strengths of MATLAB
                           Summary       Weakness of MATLAB




MATLAB is relatively easy to learn
MATLAB code is optimized to be relatively quick when
performing matrix operations
MATLAB may behave like a calculator or as a programming
language
MATLAB is interpreted, errors are easier to fix
Although primarily procedural, MATLAB does have some
object-oriented elements.




           P Bharani Chandra Kumar
Motivation     History of MATLAB
                     How it is useful for:   Strengths of MATLAB
                               Summary       Weakness of MATLAB




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation     History of MATLAB
                How it is useful for:   Strengths of MATLAB
                          Summary       Weakness of MATLAB




MATLAB is NOT a general purpose programming language
MATLAB is an interpreted language (making it for the most
part slower than a compiled language such as C++)
MATLAB is designed for scientific computation and is not
suitable for some things (such as parsing text)
MATLAB is an interpreted language, slower than a
compiled language such as C++
MATLAB commands are specific for MATLAB usage




          P Bharani Chandra Kumar
Motivation
                                             Students
                     How it is useful for:
                                             Engineers/ Scientists
                               Summary




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for students:
    System dynamics can be analysed very easily
    Messy equations can be solved very easily
    Can enhance the skills required for present jobs
    Can do the projects in a very easy way
    Can be useful for analysis and study of multi-disciplinary
    research areas




                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for students:
    System dynamics can be analysed very easily
    Messy equations can be solved very easily
    Can enhance the skills required for present jobs
    Can do the projects in a very easy way
    Can be useful for analysis and study of multi-disciplinary
    research areas




                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for students:
    System dynamics can be analysed very easily
    Messy equations can be solved very easily
    Can enhance the skills required for present jobs
    Can do the projects in a very easy way
    Can be useful for analysis and study of multi-disciplinary
    research areas




                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for students:
    System dynamics can be analysed very easily
    Messy equations can be solved very easily
    Can enhance the skills required for present jobs
    Can do the projects in a very easy way
    Can be useful for analysis and study of multi-disciplinary
    research areas




                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for students:
    System dynamics can be analysed very easily
    Messy equations can be solved very easily
    Can enhance the skills required for present jobs
    Can do the projects in a very easy way
    Can be useful for analysis and study of multi-disciplinary
    research areas




                P Bharani Chandra Kumar
Motivation
                                             Students
                     How it is useful for:
                                             Engineers/ Scientists
                               Summary




Outline

1   Motivation
      History of MATLAB
      Strengths of MATLAB
      Weakness of MATLAB


2   How it is useful for:
      Students
      Engineers/ Scientists




               P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                                              Students
                      How it is useful for:
                                              Engineers/ Scientists
                                Summary




How it is useful for Engineer/Scientists:
    Can do the research in various fields
    Contains various inbuilt blocks like electric power systems,
    IC engines, aircraft, process plant, etc .
    Need not required to struggle alot to get output as
    compared to other major packages
    Can compare the existing literature results using wide
    simulations
    Can be useful for analysis and study of multi-disciplinary
    research
    Can publish papers based on the simulations obtained



                P Bharani Chandra Kumar
Motivation
                   How it is useful for:
                             Summary




Summary
   General intro to MATLAB.
   History of MATLAB.
   Who and how it can be utilized!




             P Bharani Chandra Kumar
Motivation
                   How it is useful for:
                             Summary




Summary
   General intro to MATLAB.
   History of MATLAB.
   Who and how it can be utilized!




             P Bharani Chandra Kumar
Motivation
                   How it is useful for:
                             Summary




Summary
   General intro to MATLAB.
   History of MATLAB.
   Who and how it can be utilized!




             P Bharani Chandra Kumar
Motivation
                   How it is useful for:
                             Summary




Summary
   General intro to MATLAB.
   History of MATLAB.
   Who and how it can be utilized!




             P Bharani Chandra Kumar
Appendix    For Further Reading



For Further Reading I




     Rudra Pratap.
     Started with MATLAB : A Quick intro for Scientists and
     Engineers.
     Oxford University Press, 2006.
     www.mathworks.com




                P Bharani Chandra Kumar
Basics of MATLAB
           (Lecture 2)



P Bharani Chandra Kumar




   bharani@aero.iitb.ac.in
MATLAB GUI




               Command Window


                      Workspace

                Command History
bharani@aero.iitb.ac.in
Desktop Tools

Command Window
  type commands


Workspace
  view program variables
  clear to clear
  double click on a variable to see it in the Array Editor


Command History
  view past commands
  save a whole session using diary



             bharani@aero.iitb.ac.in
Matrices

• A vector           x = [1 2 5 1]

  x =
        1    2       5    1


• A matrix           x = [1 2 3; 5 1 4; 3 2 -1]

  x =
        1        2        3
        5        1        4
        3        2       -1


• Transpose          y = x.’          y =
                                            1
                                            2
                                            5
                                            1
                     bharani@aero.iitb.ac.in
Matrices (Contd…)
       Let,             x= [ 1     2 3
                             5     1 4
                             3     2 -1]
                             y = x(2,3)
• x(i,j) subscription
                             y =
                                   4


• whole row                  y = x(3,:)
                             y =
                                   3      2   -1
                             y = x(:,2)
• whole column
                             y =   2
                                   1
                                   2
               bharani@aero.iitb.ac.in
Operators (Arithmetic)


+   addition
-   subtraction
*   multiplication       .*    element-by-element mult
/   division             ./    element-by-element div
^   power                .^    element-by-element power
‘   complex conjugate    .‘    transpose
    transpose




              bharani@aero.iitb.ac.in
Operators (Relational, Logical)


==    equal                   pi 3.14159265…
~=    not equal               j imaginary unit,   −1
<     less than               i same as j
<=    less than or equal
>     greater than
>=    greater than or equal

&     AND
|     OR
~     NOT
             bharani@aero.iitb.ac.in
Generating Vectors from functions

                                            x = zeros(1,3)
• zeros(M,N)   MxN matrix of zeros          x =
                                              0      0     0


• ones(M,N)    MxN matrix of ones           x = ones(1,3)
                                            x =
                                              1      1    1

• rand(M,N)    MxN matrix of uniformly
                                            x = rand(1,3)
               distributed random numbers
               on (0,1)                     x =
                                                0.9501 0.2311   0.6068




                   bharani@aero.iitb.ac.in
Operators (in general)


[ ] concatenation               x = [ zeros(1,3) ones(1,2) ]
                                x =
                                     0 0 0 1 1


( ) subscription                x = [ 1 3 5 7 9]
                                x =
                                     1 3 5 7 9

                                y = x(2)
                                y =
                                     3
                                y = x(2:4)
                                y =
                                     3 5 7
                    bharani@aero.iitb.ac.in
MATRIX OPERATIONS
  Let,                 A = eye(3)

        >>     A       =   [ 1      0   0
                             0      1   0
                             0      0   1 ]

>> eig(A)      >> inv(A)            >>A'            >>A*A

ans =          ans =                ans =           ans =

  1                1   0   0            1   0   0     1     0   0
  1                0   1   0            0   1   0     0     1   0
  1                0   0   1            0   0   1     0     0   1
               bharani@aero.iitb.ac.in
MATRIX OPERATIONS (Contd…)
  Let,      >> A = [1 2 3;4 5 6;7 8 9]

              A = [       1 2 3
                          4 5 6
                           7 8 9 ]

>> eig(A)   >> B=A'         >>C=A*B        >> D=A.*B

ans =       B=              C=             D=

 16.1168      1   4   7       14 32 50      1 8 21
 -1.1168      2   5   8       32 77 122     8 25 48
 -0.0000      3   6   9       50 122 194    21 48 81
            bharani@aero.iitb.ac.in
QUESTIONS ?




bharani@aero.iitb.ac.in
Applications of MATLAB
           (Lecture 3)



P Bharani Chandra Kumar




   bharani@aero.iitb.ac.in
Overview

Linear algebra
  Solving a linear equation
  Finding eigenvalues and eigenvectors


Curve fitting and interpolation

Data analysis and statistics

Nonlinear algebraic equations



          bharani@aero.iitb.ac.in
Linear Algebra
Solving a linear system
Find the values of x, y and z for the following equations:

              5x = 3y – 2z +10
              8y +4z = 3x + 20
              2x + 4y - 9z = 9
Step 1: Rearrange equations:

               5x - 3y + 2z   = 10
               - 3x + 8y +4z = 20
               2x + 4y - 9z   = 9
Step 2: Write the equations in matrix form:
                              [A] x = b
                         5 −3 2          10 
                    A = − 3 8
                               4    b = 20
                                            
                        2
                            4 − 9
                                          9
                                            
                bharani@aero.iitb.ac.in
Linear Algebra (Contd…)
Step 3: Solve the matrix equation in MATLAB:

>> A = [ 5 -3 2; -3 8 4; 2 4 -9];
>> b = [10; 20; 9]

>> x = A b
x =
     3.442
     3.1982
      1.1868
% Veification
>> c = A*x
>> c =
      10.0000
      20.0000
      9.0000
                bharani@aero.iitb.ac.in
Linear Algebra (Contd…)
      Finding eigenvalues and eigenvectors
Eigenvalue problem in scientific computations shows up as:

                               Av=λv

The problem is to find ‘λ’ and ‘v’ for a given ‘A’ so that above eq.
is satisfied:

Method 1: Classical method by using pencil and paper:

       a) Finding eigenvalues from the determinant eqn.

                                A − λI = 0
       b) Sole for ‘n’ eigenvectors by substituting the corresponding
          eigenvalues in above eqn.
                bharani@aero.iitb.ac.in
Linear Algebra (Contd…)
Method 2: By using MATLAB:

Step 1: Enter matrix A and type [V, D] = eig(A)

>> A = [ 5 -3 2; -3 8 4; 2 4 -9];
>> [V, D] = eig(A)
V =

   -0.1709       0.8729      0.4570
   -0.2365       0.4139     -0.8791
    0.9565       0.2583     -0.1357
D =

  -10.3463            0           0
         0       4.1693           0
         0            0     10.1770

                bharani@aero.iitb.ac.in
Linear Algebra (Contd…)


Step 2: Extract what you need:

‘V’ is an ‘n x n’ matrix whose columns are eigenvectors

D is an ‘n x n’ diagonal matrix that has the eigenvalues of
‘A’ on its diagonal.




                bharani@aero.iitb.ac.in
Linear Algebra (Contd…)
Cross check:
Let us check 2nd eigenvalue and second eigenvector will
satisfy A v = λ v or not:

v2=V(:,2)     % 2nd column of V
v2 =
    0.8729
    0.4139
    0.2583

>> lam2=D(2,2)    % 2nd eigevalue
lam2 =
    4.1693
>> A*v2-lam2*v2
ans =       1.0e-014 *
                0.0444
               -0.1554
                 0.0888
             bharani@aero.iitb.ac.in
Curve Fitting
  What is curve fitting ?

   It is a technique of finding an algebraic relationship that “best”
fits a given set of data.


  There is no magical function that can give you this relationship.


  You have to have an idea of what kind of relationship might exist
between the input data (x) and output data (y).


 If you do not have a firm idea but you have data that you trust,
MATLAB can help you to explore the best possible fit.


                  bharani@aero.iitb.ac.in
Curve Fitting (Contd…)
Example 1 : straight line (linear) fit:


               x       5    10     20     50    100
               Y       15   33     53     140   301



Step 1: Plot raw data:

Enter the data in MATLAB and plot it:
       >> x = [ 5 10 20 50 100];
       >> y = [15 33 53 140 301];
       >> plot (x,y,’o’)
       >> grid


                   bharani@aero.iitb.ac.in
bharani@aero.iitb.ac.in
bharani@aero.iitb.ac.in
Curve Fitting (Contd…)
Example 2 : Comparing different fits:

             x = 0: pi/30 : pi/3
             y = sin(x) + rand (size(x))/100


Step 1: Plot raw data:
     >> plot (x,y,’o’)
     >> grid

Step 2: Use basic fitting to do a quadratic and cubic fit

Step 3 : Choose the best fit based on the residuals




               bharani@aero.iitb.ac.in
bharani@aero.iitb.ac.in
Interpolation

  What is interpolation ?

  It is a technique of finding a functional relationship between
variables such that a given set of discrete values of the variables
satisfy that relationship.

  Usually, we get a finite set of data points from experiments.

   When we want to pass a smooth curve through these points or
find some intermediate points, we use the technique of
interpolation.

  Interpolation is NOT curve fitting, in that it requires the
interpolated curve to pass through all the data points.

 Data can be interpolated using Splines or Hermite interpolants.
               bharani@aero.iitb.ac.in
Interpolation (Contd…)
  MATLAB provides        the   following   functions   to   facilitate
interpolation:

  interp1 : One data interpolation i.e. given yi and xi, finds yj at
desired xj from yj = f(xj).
               ynew = interp1(x,y,xnew, method)

   interp2 : Two dimensional data interpolation i.e. given zi at
(xi,yi) from z = f(x,y).
                  znew = interp2(x,y,z,xnew,ynew, method)

   interp3 : Three dimensional data interpolation i.e. given vi at
(xi,yi,zi) from v = f(x,y,z).
                  vnew = interp2(x,y,z,v,xnew,ynew,znew,
method)

  spline :           ynew = spline(x,y,xnew, method)
                bharani@aero.iitb.ac.in
Interpolation (Contd…)
  Example:

              x = [1        2      3   4    5    6    7   8
9]
              y = [1               4   9   16   25   36   49
64    81]
Find the value of 5.5?

  Method 1: Linear Interpolation

MATLAB Command :

        >> yi=interp1(x,y,5.5,'linear')

           yi =   30.5000


                bharani@aero.iitb.ac.in
Interpolation (Contd…)
 Method 2: Cubic Interpolation

MATLAB Command :

      >> yi =    interp1(x,y,5.5,’cubic')

          yi =
                 30.2479

 Method 3: Spline Interpolation

MATLAB Command :

      >> yi =    interp1(x,y,5.5,’spline')   Note: 5.5*5.5=

          yi =
                 30.2500
              bharani@aero.iitb.ac.in
Data Analysis and statistics

   It includes various tasks, such as finding mean, median,
standard deviation, etc.

   MATLAB provides an easy graphical interface to do such type of
tasks.

  As a first step, you should plot your data in the form you wish.

  Then go to the figure window and select data statistics from the
tools menu.

  Any of the statistical measures can be seen by checking the
appropriate box.


                 bharani@aero.iitb.ac.in
Data Analysis and statistics (Contd…)


 Example:

             x = [1     2     3    4     5     6        7   8
9]
             y = [1          4     9    16    25       36   49
64   81]


Find the minimum value, maximum value, mean, median?




              bharani@aero.iitb.ac.in
Data Analysis and statistics (Contd…)




         bharani@aero.iitb.ac.in
Data Analysis and statistics (Contd…)




         bharani@aero.iitb.ac.in
Data Analysis and statistics (Contd…)




         bharani@aero.iitb.ac.in
Data Analysis and statistics (Contd…)
It can be performed directly by using MATLAB commands also:

Consider:

                     x = [1 2 3 4 5]


mean (x) : Gives arithmetic mean of ‘x’ or the avg. data.
MATLAB usage: mean (x) gives 3.

median (x) : gives the middle value or arithmetic mean of two middle
Numbers.
MATLAB usage: median (x) gives 3.

Std(x): gives the standard deviation

Max(x)/min(x): gives the largest/smallest value
               bharani@aero.iitb.ac.in
Solving nonlinear algebraic equations
Step 1: Write the equation in the standard form:

                     f(x) = 0

Step 2: Write a function that computes f(x).

Step 3: Use the built-in function fzero to find the solution.

Example 1: Solve

                   sin x = e x − 5
Solution:

             x= fzero('sin(x)-exp(x)+5',1)

             x =
                   1.7878
                 bharani@aero.iitb.ac.in
Solving nonlinear algebraic equations
                   (contd…)

• Example 2: Solve

                               x2 − 2x + 4 = 0
 Solution:

             x= fzero(‘x*x-2*x+4',1)

             x x=e
              sin
                  =   x
                          −5
                           1.7878




                 bharani@aero.iitb.ac.in
QUESTIONS ?




bharani@aero.iitb.ac.in
Optimization Techniques
     through MATLAB
            (Lecture 4)



P Bharani Chandra Kumar



   bharani@aero.iitb.ac.in
Overview


Unconstrained Optimization

Constrained Optimization

Constrained Optimization through gradients




         bharani@aero.iitb.ac.in
Why Optimize!
Engineers are always interested in finding the
‘best’ solution to the problem at hand
  Fastest
  Fuel Efficient


Optimization theory allows engineers to
accomplish this
  Often the solution may not be easily obtained
  In the past, it has been surrounded by certain
  mistakes

            bharani@aero.iitb.ac.in
The Greeks started it!
Queen Dido of Carthage (7 century
BC)
 – Daughter of the king of Tyre
 – Agreed to buy as much land as
   she could “enclose with one
   bull’s hide”
 – Set out to choose the largest
   amount of land possible, with
   one border along the sea
    • A semi-circle with side
      touching the ocean
    • Founded Carthage
 – Fell in love with Aeneas but
   committed suicide when he left.



               bharani@aero.iitb.ac.in
The Italians Countered
Joseph Louis Lagrange (1736-1813)
  His work Mécanique Analytique (Analytical
  Mechanics) (1788) was a mathematical
  masterpiece
  Invented the method of ‘variations’ which
  impressed Euler and became ‘calculus of
  variations’
  Invented the method         of    multipliers
  (Lagrange multipliers)
     Sensitivities of the performance index to
     changes in states/constraints
  Became the      ‘father’   of    ‘Lagrangian’
  Dynamics
     Euler-Lagrange Equations
             bharani@aero.iitb.ac.in
The Multi-Talented Mr. Euler
Euler (1707-1783)
   Friend of Lagrange
   Published a treatise which became
   the de facto standard of the
   ‘calculus of variations’
      The Method of Finding Curves
      that Show Some Property of
      Maximum or Minimum
   He solved the brachistachrone
   (brachistos = shortest, chronos =
   time) problem very easily
      Minimum time path for a bead
      on a string, Cycloid

                bharani@aero.iitb.ac.in
Hamilton and Jacobi
William Hamilton (1805-1865)
   Inventor of the quaternion


Karl Gustav Jacob Jacobi (1804-
1851)
   Discovered ‘conjugate points’ in
   the fields of extremals
   Gave an insightful treatment to
   the second variation


Jacobi criticized Hamilton’s work
   Hamilton-Jacobi equation
   Became the basis of Bellman’s
   work 100 years later

               bharani@aero.iitb.ac.in
What to Optimize?
Engineers intuitively know       what   they   are
interested in optimizing

  Straightforward problems
     Fuel
     Time
     Power
     Effort
  More complex
     Maximum margin
     Minimum risk
The mathematical quantity we optimize is called
a cost function or performance index
            bharani@aero.iitb.ac.in
Optimization through MATLAB
  Consider initially the problem of finding a minimum
to the function:


  MATLAB function FMINCON solves problems of the form:

                    min F(X)

subject to:   A*X <= B, Aeq*X = Beq (linear constraints)

              C(X) <= 0, Ceq(X) = 0   (nonlinear constraints)

              LB <= X <= UB




                bharani@aero.iitb.ac.in
Optimization through MATLAB
               (Contd…)

   X = FMINCON(FUN,X0,A,B) starts at X0 and finds a minimum
X to the function FUN, subject to the linear inequalities A*X <= B.




    X=FMINCON(FUN,X0,A,B,Aeq,Beq) minimizes FUN subject to
the linear equalities:

               Aeq*X = Beq as well as A*X <= B.

           (Set A=[ ] and B=[ ] if no inequalities exist.)



                 bharani@aero.iitb.ac.in
Optimization through MATLAB
                (Contd…)
    X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB) defines a set of
lower and upper bounds on the design variables, X, so that the
solution is in the range LB <= X <= UB.

Use empty matrices for LB and UB if no bounds exist.
Set LB(i) = -Inf if X(i) is unbounded below; and set UB(i) = Inf if X(i)
is unbounded above.

    X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON) subjects
the minimization to the constraints defined in NONLCON.

The function NONLCON accepts X and returns the vectors C and
Ceq, representing the nonlinear inequalities and equalities
respectively.


                  bharani@aero.iitb.ac.in
Unonstrained Optimization : Example
  Consider the above problem with no constraints:

                  f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1)

  Solution by MATLAB:

 Step 1: Create an inline object of the function to be minimized
fun = inline('exp(x(1)) * (4*x(1)^2 + 2*x(2)^2 +
4*x(1)*x(2) + 2*x(2) + 1)');

Step 2: Take a guess at the solution:
               x0 = [-1 1];

Step 3: Solve using fminunc function:
   [x, fval] = fminunc(fun, x0);

                 bharani@aero.iitb.ac.in
Unconstrained Optimization : Example
                (Contd…)
>> x =

   0.5000   -1.0000


>> fval =

 1.3028e-010




               bharani@aero.iitb.ac.in
Constrained Optimization : Example
  Consider initially the problem of finding a minimum
to the function:
                  f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1)

Subjected to:

                1.5 + x(1).x(2) - x(1) - x(2) < = 0

                       - x(1).x(2)                     < = 10




                  bharani@aero.iitb.ac.in
Constrained Optimization : Example
                  (contd…)
  Solution using MATLAB:

Step 1: Write the m-file for objective function:

function f = objfun(x)
% objective function
f=exp(x(1)) * (4*x(1)^2 + 2*x(2)^2 + 4*x(1)*x(2) +
2*x(2) + 1);

Step 2: Write the m-file for constraints:
function [c, ceq] = confun(x)
% Nonlinear inequality constraints:
c = [1.5 + x(1)*x(2) - x(1) - x(2);
     -x(1)*x(2) - 10];
% no nonlinear equality constraints:
ceq = [];
                  bharani@aero.iitb.ac.in
Constrained Optimization : Example
                 (contd…)
Step 3: Take a guess at the solution
x0 = [-1 1];

options =
optimset('LargeScale','off','Display','iter');


% We have no linear equalities or inequalities or
bounds,
%   so pass [] for those arguments

[x,fval,exitflag,output] =
fmincon('objfun',x0,[],[],[],[],[],[],'confun',options)
;



             bharani@aero.iitb.ac.in
max                                                           Directional
  Iter   F-count      f(x)         constraint     Step-size        derivative
   Procedure
    1      3         1.8394          0.5             1           0.0486
    2      7        1.85127     -0.09197             1           -0.556    Hessian
   modified twice
    3     11       0.300167         9.33             1              0.17
    4     15       0.529834       0.9209             1            -0.965
    5     20       0.186965       -1.517           0.5            -0.168
    6     24      0.0729085       0.3313             1           -0.0518
    7     28      0.0353322     -0.03303             1           -0.0142
    8     32      0.0235566     0.003184             1        -6.22e-006
    9     36      0.0235504   9.032e-008             1         1.76e-010   Hessian
   modified
 Optimization terminated successfully:


% A solution to this problem has been found at:
x

x =

   -9.5474   1.0474




                       bharani@aero.iitb.ac.in
% The function value at the solution is:
fval

fval =

      0.0236

% Both the constraints are active at the solution:
[c, ceq] = confun(x)

c =

  1.0e-014 *

    0.1110
   -0.1776


ceq =

       []




                    bharani@aero.iitb.ac.in
QUESTIONS ?




bharani@aero.iitb.ac.in
System Identification
           (Lecture 5)



P Bharani Chandra Kumar




   bharani@aero.iitb.ac.in
Overview

Introduction

Basic questions about system identification

Common terms used in system identification

Basic information about dynamical systems

Basic steps for system identification

An exciting example

          bharani@aero.iitb.ac.in
Introduction

What is system identification?



                  Water       Can you Say
                  Heater      What is this!

Cold Water                       Hot Water




             bharani@aero.iitb.ac.in
What is system identification?

Determining system dynamics from input-output
data

  Generate enough      data    for   estimation   and
  validation

  Select range for estimation and validation

  Select order of the system

  Check for best fit and determine the system
  dynamics
           bharani@aero.iitb.ac.in
Basic questions about system
           identification

What is system identification?

It enables you to build mathematical models of a
dynamic system based on measured data.

You adjust the parameters of a given model until its
output coincides as well as possible with the
measured output.

How do you know if the model is any good?
A good test is to compare the output of the model to
measured data that was not used for the fit.
            bharani@aero.iitb.ac.in
Basic questions about system
         identification (contd…)

  What models are most common?
  The most common models are difference-equation
  descriptions, such as ARX and ARMAX models, as
  well as all types of linear state-space models.

• Do you have to assume a model of a particular
  type?
  For parametric models, you specify the model
  structure. This can be as easy as selecting a single
  integer -- the model order -- or it can involve several
  choices.


               bharani@aero.iitb.ac.in
Basic questions about system
        identification (contd…)

  What does the System Identification Toolbox
  contain?
  It contains all the common techniques used to
  adjust parameters in all kinds of linear models.

• How do I get started?
  If you are a beginner, browse through The
  Graphical User Interface. Use the graphical user
  interface (GUI) and check out the built-in help
  functions.



             bharani@aero.iitb.ac.in
Basic questions about system
       identification (contd…)

Is this really all there is to system identification?

There is a great deal written on the subject of
system identification.

However, the best way to explore                 system
identification is by working with real data.

 It is important to remember that any estimated
model, no matter how good it looks on your screen,
is only a simplified reflection of reality.

             bharani@aero.iitb.ac.in
Common terms used in system
        identification

Estimation data: The data set that is used to create
a model of the data.

Validation data: The data set (different from
estimation data) that is used to validate the model.

Model views: The various ways of inspecting the
properties of a model, such as zeros and poles, as
well as transient and frequency responses.




            bharani@aero.iitb.ac.in
Common terms used in system
     identification (contd…)

Model sets or model structures are families of
models with adjustable parameters.

Parameter estimation is the process of finding the
"best" values of these adjustable parameters.

The system identification problem is to find both
the model structure and good numerical values of
the model parameters.




           bharani@aero.iitb.ac.in
Common terms used in system
        identification (contd…)


• This is a matter of using numerical search to find
  those numerical values of the parameters that give
  the best agreement between the model's (simulated
  or predicted) output and the measured output.

• Nonparametric identification methods: Techniques
  to estimate model behavior without necessarily
  using a given parameterized model set.

• Model validation is      the   process   of   gaining
  confidence in a model.
              bharani@aero.iitb.ac.in
Basic information about dynamical
             systems




        bharani@aero.iitb.ac.in
Basic Steps for System
            Identification

Import data from the MATLAB workspace.

Plot the data using Data Views.

 Preprocess the data      using   commands     in   the
Preprocess menu.

For example, you can remove constant offsets or
linear trends (for linear models only), filter data, or
select regions of interest.


            bharani@aero.iitb.ac.in
Basic Steps for System
      Identification (contd…)

Select estimation and validation data.

Estimate models using commands in the Estimate
menu.

Validate models using Models Views.

Export models to the MATLAB workspace for
further processing .




          bharani@aero.iitb.ac.in
QUESTIONS ?




bharani@aero.iitb.ac.in
Solution of Ordinary Differential
Equations and Engineering Computing

               (Lecture 6)



   P Bharani Chandra Kumar

       bharani@aero.iitb.ac.in
Solution of Ordinary Differential
            Equaions




    bharani@aero.iitb.ac.in
Overview

Introduction

Examples




           bharani@aero.iitb.ac.in
Introduction
DSOLVE Symbolic solution of ordinary differential
equations.

DSOLVE('eqn1','eqn2',     ...)    accepts   symbolic
equations   representing       ordinary   differential
equations and initial conditions.

Several equations or initial conditions may be
grouped together, separated by commas, in a single
input argument.

By default, the independent variable is 't'.

The independent variable may be changed from 't'
to some other symbolic variable by including
that variable as the last input argument.
           bharani@aero.iitb.ac.in
Introduction (contd…)

The letter 'D' denotes differentiation with respect
to the independent variable, i.e. usually d/dt.

A "D" followed by a digit denotes repeated
differentiation; e.g., D2 is d^2/dt^2.

Any characters immediately following these
differentiation operators are taken to be the
dependent variables; e.g., D3y denotes the third
derivative of y(t).

Note that the names of symbolic variables should
not contain the letter "D".

           bharani@aero.iitb.ac.in
Introduction (contd…)

Initial conditions are specified by equations like
'y(a)=b' or 'Dy(a) = b' where y is one of the
dependent variables and a and b are
constants.

If the number of initial conditions given is less
than the number of dependent variables, the
resulting   solutions   will   obtain   arbitrary
constants, C1, C2, etc.

Three different types of output are possible. For
one equation and one output, the resulting
solution is returned, with multiple solutions to
a nonlinear equation in a symbolic vector.

          bharani@aero.iitb.ac.in
Introduction (contd…)

If no closed-form (explicit) solution is found, an
implicit solution is attempted. When an implicit
solution is returned, a warning is given.

If neither an explicit nor implicit solution can be
computed, then a warning is given and the
empty sym is returned.

In some cases concerning nonlinear equations,
the output will be an equivalent lower order
differential equation or an integral.




           bharani@aero.iitb.ac.in
Examples
1) dsolve('Dx = -a*x') returns

  ans: exp(-a*t)*C1

 2) x = dsolve('Dx = -a*x','x(0) = 1','s') returns

  ans: x = exp(-a*s)

 3) y = dsolve('(Dy)^2 + y^2 = 1','y(0) = 0') returns
  ans:     y=
      [ sin(t)]
      [ -sin(t)]


              bharani@aero.iitb.ac.in
Examples (contd…)


4) S = dsolve('Df = f + g','Dg = -f + g','f(0) = 1','g(0) = 2')

Ans: S.f = exp(t)*cos(t)+2*exp(t)*sin(t)
     S.g = -exp(t)*sin(t)+2*exp(t)*cos(t)



5) dsolve('Df = f + sin(t)', 'f(pi/2) = 0')

Ans: -1/2*cos(t)- 1/2*sin(t)+1/2*exp(t)/(cosh(1/2*pi)+
      sinh(1/2*pi))
               bharani@aero.iitb.ac.in
Engineering Computing




bharani@aero.iitb.ac.in
Outline of lecture


MATLAB as a calculator revisited

Concept of M-files

Decision making in MATLAB

Use of IF and ELSEIF commands

Example: Real roots of a quadratic


         bharani@aero.iitb.ac.in
MATLAB as a calculator


MATLAB can be used as a ‘clever’ calculator
  This has very limited value in engineering

Real value of MATLAB is in programming
  Want to store a set of instructions
  Want to run these instructions sequentially
  Want the ability to input data and output
  results
  Want to be able to plot results
  Want to be able to ‘make decisions’
         bharani@aero.iitb.ac.in
Example

     n
           1    1    1    1
y=∑           =    +    +    + ...
    i =1    i    1    2    3

Can do using MATLAB as a calculator
 >> x = 1:10;
 >> term = 1./sqrt(x);
 >> y = sum(term);

Far easier to write as an M-file


            bharani@aero.iitb.ac.in
How to write an M-file


File → New → M-file

Takes you into the file editor

Enter lines of code (nothing happens)

Save file (we will call ours bharani.m)

Run file

Edit (ie modify) file if necessary


             bharani@aero.iitb.ac.in
Bharani.m Version 1


n = input(‘Enter the upper limit: ‘);
x = 1:n;           % Matlab is case sensitive
term = sqrt(x);
y = sum(term)

What happens if n < 1 ?




            bharani@aero.iitb.ac.in
Bharani.m Version 2


n = input(‘Enter the upper limit: ‘);
if n < 1
     disp (‘Your answer is meaningless!’)
end
x = 1:n;
term = sqrt(x);                  Jump to here if TRUE
y = sum(term)

                                Jump to here if FALSE


             bharani@aero.iitb.ac.in
Decision making in MATLAB


For ‘simple’ decisions?
IF … END (as in last example)
More complex decisions?
IF … ELSEIF … ELSE ... END

Example: Real roots of a quadratic equation




            bharani@aero.iitb.ac.in
Roots of ax2+bx+c=0


Roots set by discriminant          − b ± b 2 − 4ac
∆ < 0 (no real roots)
                                x=
                                         2a
∆ = 0 (one real root)
∆ > 0 (two real roots)
                                        2
MATLAB needs to make
                                ∆ = b − 4ac
  decisions (based on ∆)




              bharani@aero.iitb.ac.in
One possible M-file
Read in values of a, b, c
Calculate ∆
IF ∆ < 0
Print message ‘ No real roots’→ Go END
ELSEIF ∆ = 0
Print message ‘One real root’→ Go END
ELSE
Print message ‘Two real roots’
END



          bharani@aero.iitb.ac.in
M-file (bharani.m)
%================================================
% Demonstration of an m-file
% Calculate the real roots of a quadratic equation
%================================================

clear all;    % clear all variables
clc;         % clear screen

coeffts = input('Enter values for a,b,c (as a vector): ');

 % Read in equation coefficients
a = coeffts(1);
b = coeffts(2);
c = coeffts(3);

delta = b^2 - 4*a*c;    % Calculate discriminant

                bharani@aero.iitb.ac.in
M-file (bharani.m) (contd…)
% Calculate number (and value) of real roots

if delta < 0

  fprintf('nEquation has no real roots:nn')
  disp(['discriminant = ', num2str(delta)])

elseif delta == 0
   fprintf('nEquation has one real root:n')
   xone = -b/(2*a)
else
   fprintf('nEquation has two real roots:n')
   x(1) = (-b + sqrt(delta))/(2*a);
   x(2) = (-b – sqrt(delta))/(2*a);
   fprintf('n First root = %10.2ent Second root = %10.2f',
   x(1),x(2))
end
               bharani@aero.iitb.ac.in
Conclusions


  MATLAB is more than a calculator
      its a powerful programming environment


• Have reviewed:
  –   Concept of an M-file
  –   Decision making in MATLAB
  –   IF … END and IF … ELSEIF … ELSE … END
  –   Example of real roots for quadratic equation




                bharani@aero.iitb.ac.in
QUESTIONS ?




bharani@aero.iitb.ac.in
Graphics


      By
 G Satish
Outline
 2-D plots
 3-D plots
 Handle objects
2-D plots
Simple plot
>> a=[1 2 3 4]
>> plot(a)
Overlay plots
 using plot command
    >> t=0:pi/10:2*pi;
    >> y=sin(t); z=cos(t);
    >> plot(t,y,t,z)
Overlay plots(contd…)
 using hold command
    >> plot(t,sin(t));
    >> grid
    >> hold
    >> plot(t,sin(t))
Overlay plots(contd..)
  using line command
     >> t=linspace(0,2*pi,10)
     >> y=sin(t); y2=t; y3=(t.^3)/6+(t.^5)/120;
     >> plot(t,y1)
     >> line(t,y2,’linestyle’,’--’)
     >> line(t,y3,’marker’,’o’)
Overlay plots
Style options
>> t=0:pi/10:2*pi;
>> y=sin(t); z=cos(t);
>>plot(t,y,’go-’,t,z,’b*--’)
Style options
   b   blue       . point           - solid
   g   green     o circle           : dotted
   r   red        x x-mark           -. dashdot
   c   cyan      + plus             -- dashed
   m   magenta   * star
   y   yellow     s square
   k   black     d diamond
                  v triangle (down)
                  ^ triangle (up)
                  < triangle (left)
                  > triangle (right)
                  p pentagram
                  h hexagram
Labels, title, legend and other text
objects

>> a=[1 2 3 4]; b=[ 1 2 3 4]; c=[4 5 6 7]
>> plot(a,b,a,c)
>> grid
>> xlabel(‘xaxis’)
>> ylabel(‘yaxis’)
>> title(‘example’)
>> legend(‘first’,’second’)
>> text(2,6,’plot’)
Modifying plots with the plot editor
 To activate this tool go to
 figure window and click on the
 left-leaning arrow
 Now you can select and
 double click on any object in
 the current plot to edit it.
 Double clicking on the selected
 object brings up a property
 editor window where you can
 select and modify the current
 properties of the object
Subplots
>> t=linspace(0,2*pi,10); y=sin(t); z=cos(t);
>> figure
>> subplot(2,1,1)
>> subplot(2,1,2)
>> subplot(2,1,1); plot(t,y)
>> subplot(2,1,2); plot(t,z)
Logarthmic plots
>> x=0:0.1:2*pi;
>>subplot(2,2,1)
>> semilogx(x,exp(-x));
>> grid

>> subplot(2,2,2)
>> semilogy(a,b);
>> grid

>> subplot(2,2,3)
>> loglog(x,exp(-x));
>> grid
Zoom in and zoom out
>> figure
>> plot(t,sin(t))
>> axis([0 2 -2 2])
Specialised plotting routines
>> stem(t,sin(t));
>> bar(t,sin(t))
>> a=[1 2 3 4]; stairs(a);
3-D plots
Simple 3-D plot
 Plot of a parametric space curve
    >> t=linspace(0,1,100);
    >> x=t; y=t; z=t.^3;
    >> plot3(x,y,z); grid
View
>> t=linspace(0,6*pi,100);
>> x=cos(t); y=sin(t); z=t;
>> subplot(2,2,1); plot3(x,y,z);
>> subplot(2,2,2); plot3(x,y,z); view(0,90);
>> subplot(2,2,3); plot3(x,y,z); view(0,0);
>> subplot(2,2,4); plot3(x,y,z); view(90,0);
View (contd…)
Mesh plots
>> x=linspace(-3,3,50);
>> [X,Y]= meshgrid(x,y);
>> Z=X.*Y.*(X.^2-Y.^2)./(X.^2+Y.^2);
>> mesh(X,Y,Z);
>> figure(2)
Mesh plots(cont…)
Surface plots
>> u = -5 : 0.2 : 5;
>> [X,Y] = meshgrid(u,u);
>> Z=cos(X).*cos(Y).*exp(-sqrt(X.^2+Y.^2)/4);
>> surf(X,Y,Z)
Surface plots (contd…)
Handle Graphics
Handle Graphics Objects
 Handle Graphics is an object-oriented
 structure for creating, manipulating and
 displaying graphics
 Graphics in Matlab consist of objects
 Every graphics objects has:
    – a unique identifier, called handle
    – a set of characteristics, called properties
Getting object handles
 There are two ways for getting object handles
 •   By creating handles explicitly at the object-
     creation level commands
 •   By using explicit handle return functions
Getting object handles
 By creating handles explicitly at the object-
 creation level commands
    >> hfig=figure
    >> haxes=axes(‘position’,[0.1 0.1 0.4 0.4])
    >> t=linspace(0,pi,10);
    >> hL = line(t,sin(t))
    >> hx1 = xlabel(‘Angle’)
Getting object handles
 By using explicit handle return functions
    >> gcf     gets the handle of the current
               figure
    >> gca     gets handle of current axes
    >> gco     returns the current object in the
               current figure
Getting object handles
 Example
    >> figure
    >> axes
    >> line([1 2 3 4],[1 2 3 4])
    >> hfig = gcf
    >> haxes = gca
          Click on the line in figure
    >>hL=gco
Getting properties of objects
 The function ‘get’ is used to get a property
 value of an object specified by its handle
   get(handle,’PropertyName’)
 The following command will get a list of all
 property names and their current values of an
 object with handle h
   get(h)
Getting properties of objects
 Example
  >> h1=plot([ 1 2 3 4]);returns a line
     object
  >> get(h1)
  >> get(h1,’type’)
  >> get(h1,’linestyle’)
Setting properties of objects
 The properties of the objects can be set by
 using ‘set’ command which has the following
 command form
   Set(handle, ‘PropertyName’,Propertyvalue’)
 By using following command you can see the
 the list of properties and their values
   Set(handle)
Setting properties of objects
 example
 >> t=linspace(0,pi,50);
 >> x=t.*sin(t);
 >> hL=line(t,x);
Setting properties of objects
>> set(hL,’linestyle’,’--’);
Setting properties of objects
>> set(hL,’linewidth’,3,’marker’,’o’)
Setting properties of objects
>> yvec = get(hL,’ydata’);
>> yvec(15:20) = 0;
>> yvec(40:45) = 0;
>> set(hL, ’ydata’, yvec)
Creating subplots using axes
command
 >> hfig=figure
 >> ha1=axes(‘position’,[0.1 0.5 0.3 0.3])
 >> line([1 2 3 4],[1 2 3 4])

 >> ha2=axes(‘position’[0.5 0.5 0.3 0.3])
 >> line([1 2 3 4],[ 1 10 100 1000])

 >> ha3=axes(‘position’,[0.1 0.1 0.3 0.3])
 >> line([1 2 3 4],[0.1 0.2 0.3 0.4])

 >> ha4=axes(‘position’,[0.5 0.1 0.3 0.3])
 >> line([1 2 3 4],[10 10 10 10])

Más contenido relacionado

La actualidad más candente

Circuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modelingCircuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modelingIndra S Wahyudi
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IVijay Kumar Gupta
 
MATLAB/SIMULINK for engineering applications: day 3
MATLAB/SIMULINK for engineering applications: day 3MATLAB/SIMULINK for engineering applications: day 3
MATLAB/SIMULINK for engineering applications: day 3reddyprasad reddyvari
 
application based Presentation on matlab simulink & related tools
application based Presentation on matlab simulink & related toolsapplication based Presentation on matlab simulink & related tools
application based Presentation on matlab simulink & related toolsEshaan Verma
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab IntroductionDaniel Moore
 
Matlab day 1: Introduction to MATLAB
Matlab day 1: Introduction to MATLABMatlab day 1: Introduction to MATLAB
Matlab day 1: Introduction to MATLABreddyprasad reddyvari
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlabArshit Rai
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingMatlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingDr. Manjunatha. P
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introductionAmeen San
 
Multi Processor Architecture for image processing
Multi Processor Architecture for image processingMulti Processor Architecture for image processing
Multi Processor Architecture for image processingideas2ignite
 
Matlab for Electrical Engineers
Matlab for Electrical EngineersMatlab for Electrical Engineers
Matlab for Electrical EngineersManish Joshi
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)Retheesh Raj
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Chetan Allapur
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLABRavikiran A
 
Summer training on matlab
Summer training on matlabSummer training on matlab
Summer training on matlabdangerahad
 

La actualidad más candente (20)

Matlab brochure
Matlab  brochureMatlab  brochure
Matlab brochure
 
Circuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modelingCircuit analysis i with matlab computing and simulink sim powersystems modeling
Circuit analysis i with matlab computing and simulink sim powersystems modeling
 
Matlab
MatlabMatlab
Matlab
 
MATLAB INTRODUCTION
MATLAB INTRODUCTIONMATLAB INTRODUCTION
MATLAB INTRODUCTION
 
Matlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - IMatlab Tutorial for Beginners - I
Matlab Tutorial for Beginners - I
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
MATLAB/SIMULINK for engineering applications: day 3
MATLAB/SIMULINK for engineering applications: day 3MATLAB/SIMULINK for engineering applications: day 3
MATLAB/SIMULINK for engineering applications: day 3
 
application based Presentation on matlab simulink & related tools
application based Presentation on matlab simulink & related toolsapplication based Presentation on matlab simulink & related tools
application based Presentation on matlab simulink & related tools
 
Matlab Introduction
Matlab IntroductionMatlab Introduction
Matlab Introduction
 
Matlab day 1: Introduction to MATLAB
Matlab day 1: Introduction to MATLABMatlab day 1: Introduction to MATLAB
Matlab day 1: Introduction to MATLAB
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlab
 
Matlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processingMatlab for beginners, Introduction, signal processing
Matlab for beginners, Introduction, signal processing
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 
Multi Processor Architecture for image processing
Multi Processor Architecture for image processingMulti Processor Architecture for image processing
Multi Processor Architecture for image processing
 
Matlab for Electrical Engineers
Matlab for Electrical EngineersMatlab for Electrical Engineers
Matlab for Electrical Engineers
 
Matlab for diploma students(1)
Matlab for diploma students(1)Matlab for diploma students(1)
Matlab for diploma students(1)
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Summer training on matlab
Summer training on matlabSummer training on matlab
Summer training on matlab
 
Matlab Basic Tutorial
Matlab Basic TutorialMatlab Basic Tutorial
Matlab Basic Tutorial
 

Destacado

Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to MatlabTariq kanher
 
MATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaMATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaAbee Sharma
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to MatlabAmr Rashed
 
Matlab Mech Eee Lectures 1
Matlab Mech Eee Lectures 1Matlab Mech Eee Lectures 1
Matlab Mech Eee Lectures 1Ayyarao T S L V
 
An introduction to FACTS
An introduction to FACTSAn introduction to FACTS
An introduction to FACTSAyyarao T S L V
 
Matlab practical and lab session
Matlab practical and lab sessionMatlab practical and lab session
Matlab practical and lab sessionDr. Krishna Mohbey
 
Power Flow in a Transmission line
Power Flow in a Transmission linePower Flow in a Transmission line
Power Flow in a Transmission lineAyyarao T S L V
 
Static shunt compensation
Static shunt compensationStatic shunt compensation
Static shunt compensationAyyarao T S L V
 
Matlab Introduction by Jiing
Matlab Introduction by JiingMatlab Introduction by Jiing
Matlab Introduction by Jiingjiing deng
 
An introduction to FACTS Technology
An introduction to FACTS TechnologyAn introduction to FACTS Technology
An introduction to FACTS TechnologyAyyarao T S L V
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLABBhavesh Shah
 
matlab simulink مكتبة العناصر المستمرة
  matlab simulink مكتبة العناصر المستمرة  matlab simulink مكتبة العناصر المستمرة
matlab simulink مكتبة العناصر المستمرةHasan Edrees
 
Simulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleSimulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleKamran Gillani
 
matlab,simulink-simulinkmodelingtutorial
matlab,simulink-simulinkmodelingtutorialmatlab,simulink-simulinkmodelingtutorial
matlab,simulink-simulinkmodelingtutorialdhanniell
 
Mat lab solving equations simulink
Mat lab solving equations simulinkMat lab solving equations simulink
Mat lab solving equations simulinkAmeen San
 
Objectives of shunt compensation
Objectives of shunt compensationObjectives of shunt compensation
Objectives of shunt compensationAyyarao T S L V
 

Destacado (20)

Brief Introduction to Matlab
Brief  Introduction to MatlabBrief  Introduction to Matlab
Brief Introduction to Matlab
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
MATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi SharmaMATLAB Programs For Beginners. | Abhi Sharma
MATLAB Programs For Beginners. | Abhi Sharma
 
Introduction to Matlab
Introduction to MatlabIntroduction to Matlab
Introduction to Matlab
 
Matlab
MatlabMatlab
Matlab
 
Matlab Mech Eee Lectures 1
Matlab Mech Eee Lectures 1Matlab Mech Eee Lectures 1
Matlab Mech Eee Lectures 1
 
An introduction to FACTS
An introduction to FACTSAn introduction to FACTS
An introduction to FACTS
 
Matlab practical and lab session
Matlab practical and lab sessionMatlab practical and lab session
Matlab practical and lab session
 
Power Flow in a Transmission line
Power Flow in a Transmission linePower Flow in a Transmission line
Power Flow in a Transmission line
 
Static shunt compensation
Static shunt compensationStatic shunt compensation
Static shunt compensation
 
Matlab Introduction by Jiing
Matlab Introduction by JiingMatlab Introduction by Jiing
Matlab Introduction by Jiing
 
Ballas1
Ballas1Ballas1
Ballas1
 
An introduction to FACTS Technology
An introduction to FACTS TechnologyAn introduction to FACTS Technology
An introduction to FACTS Technology
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
matlab simulink مكتبة العناصر المستمرة
  matlab simulink مكتبة العناصر المستمرة  matlab simulink مكتبة العناصر المستمرة
matlab simulink مكتبة العناصر المستمرة
 
Simulink - Introduction with Practical Example
Simulink - Introduction with Practical ExampleSimulink - Introduction with Practical Example
Simulink - Introduction with Practical Example
 
matlab,simulink-simulinkmodelingtutorial
matlab,simulink-simulinkmodelingtutorialmatlab,simulink-simulinkmodelingtutorial
matlab,simulink-simulinkmodelingtutorial
 
Simulink
SimulinkSimulink
Simulink
 
Mat lab solving equations simulink
Mat lab solving equations simulinkMat lab solving equations simulink
Mat lab solving equations simulink
 
Objectives of shunt compensation
Objectives of shunt compensationObjectives of shunt compensation
Objectives of shunt compensation
 

Similar a Matlab Mech Eee Lectures 1

MATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptMATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptssuserdee4d8
 
MATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptMATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptaboma2hawi
 
Matlab-Assignment-Help-Turkey
Matlab-Assignment-Help-TurkeyMatlab-Assignment-Help-Turkey
Matlab-Assignment-Help-TurkeyPhdtopiccom
 
Summer training introduction to matlab
Summer training  introduction to matlabSummer training  introduction to matlab
Summer training introduction to matlabArshit Rai
 
INTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptINTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptKarthik537368
 
MATLAB'S PRESENTS1.pptx
MATLAB'S  PRESENTS1.pptxMATLAB'S  PRESENTS1.pptx
MATLAB'S PRESENTS1.pptxNikhilPadole5
 
Matlab - Introduction and Basics
Matlab - Introduction and BasicsMatlab - Introduction and Basics
Matlab - Introduction and BasicsTechsparks
 
Getting to know about Matrix Laboratory or MatLab.pptx
Getting to know about Matrix Laboratory or MatLab.pptxGetting to know about Matrix Laboratory or MatLab.pptx
Getting to know about Matrix Laboratory or MatLab.pptxSample Assignment
 
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Ahmed Gad
 
A comprehensive guide on the uses of MATLAB
A comprehensive guide on the uses of MATLABA comprehensive guide on the uses of MATLAB
A comprehensive guide on the uses of MATLABStat Analytica
 
Basics of matlab i
Basics of matlab iBasics of matlab i
Basics of matlab issusera9e62b
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLABkalaimuthu2
 
A comprehensive guide on the uses of MATALAB
A comprehensive guide on the uses of MATALABA comprehensive guide on the uses of MATALAB
A comprehensive guide on the uses of MATALABStat Analytica
 
MATLAB Research Thesis Help
MATLAB Research Thesis Help MATLAB Research Thesis Help
MATLAB Research Thesis Help Matlab Simulation
 

Similar a Matlab Mech Eee Lectures 1 (20)

Introduction of Matlab
Introduction of Matlab Introduction of Matlab
Introduction of Matlab
 
matlab1.pptx
matlab1.pptxmatlab1.pptx
matlab1.pptx
 
matlab new.pptx
matlab new.pptxmatlab new.pptx
matlab new.pptx
 
MATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.pptMATLAB workshop lecture 1MATLAB work.ppt
MATLAB workshop lecture 1MATLAB work.ppt
 
MATLAB_CIS601-03.ppt
MATLAB_CIS601-03.pptMATLAB_CIS601-03.ppt
MATLAB_CIS601-03.ppt
 
Matlab-Assignment-Help-Turkey
Matlab-Assignment-Help-TurkeyMatlab-Assignment-Help-Turkey
Matlab-Assignment-Help-Turkey
 
Summer training introduction to matlab
Summer training  introduction to matlabSummer training  introduction to matlab
Summer training introduction to matlab
 
INTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.pptINTRODUCTION TO MATLAB for PG students.ppt
INTRODUCTION TO MATLAB for PG students.ppt
 
MATLAB'S PRESENTS1.pptx
MATLAB'S  PRESENTS1.pptxMATLAB'S  PRESENTS1.pptx
MATLAB'S PRESENTS1.pptx
 
Matlab.pdf
Matlab.pdfMatlab.pdf
Matlab.pdf
 
Matlab - Introduction and Basics
Matlab - Introduction and BasicsMatlab - Introduction and Basics
Matlab - Introduction and Basics
 
Getting to know about Matrix Laboratory or MatLab.pptx
Getting to know about Matrix Laboratory or MatLab.pptxGetting to know about Matrix Laboratory or MatLab.pptx
Getting to know about Matrix Laboratory or MatLab.pptx
 
Primer
PrimerPrimer
Primer
 
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
Introduction to MATrices LABoratory (MATLAB) as Part of Digital Signal Proces...
 
A comprehensive guide on the uses of MATLAB
A comprehensive guide on the uses of MATLABA comprehensive guide on the uses of MATLAB
A comprehensive guide on the uses of MATLAB
 
Basics of matlab i
Basics of matlab iBasics of matlab i
Basics of matlab i
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
A comprehensive guide on the uses of MATALAB
A comprehensive guide on the uses of MATALABA comprehensive guide on the uses of MATALAB
A comprehensive guide on the uses of MATALAB
 
MATLAB Research Thesis Help
MATLAB Research Thesis Help MATLAB Research Thesis Help
MATLAB Research Thesis Help
 
MATLAB Training
MATLAB TrainingMATLAB Training
MATLAB Training
 

Más de Ayyarao T S L V

A Review and Aspects of High Altitude Wind Power Generation
A Review and Aspects of High Altitude Wind Power GenerationA Review and Aspects of High Altitude Wind Power Generation
A Review and Aspects of High Altitude Wind Power GenerationAyyarao T S L V
 
Basic types of facts controllers
Basic types of facts controllersBasic types of facts controllers
Basic types of facts controllersAyyarao T S L V
 
Adaptive control of saturated induction motor with uncertain load torque
Adaptive control of saturated induction motor with uncertain load torqueAdaptive control of saturated induction motor with uncertain load torque
Adaptive control of saturated induction motor with uncertain load torqueAyyarao T S L V
 

Más de Ayyarao T S L V (9)

A Review and Aspects of High Altitude Wind Power Generation
A Review and Aspects of High Altitude Wind Power GenerationA Review and Aspects of High Altitude Wind Power Generation
A Review and Aspects of High Altitude Wind Power Generation
 
Basic types of facts controllers
Basic types of facts controllersBasic types of facts controllers
Basic types of facts controllers
 
Drives
DrivesDrives
Drives
 
Hydrogenerator
HydrogeneratorHydrogenerator
Hydrogenerator
 
Adaptive control of saturated induction motor with uncertain load torque
Adaptive control of saturated induction motor with uncertain load torqueAdaptive control of saturated induction motor with uncertain load torque
Adaptive control of saturated induction motor with uncertain load torque
 
INDUCTION MOTOR1
INDUCTION MOTOR1INDUCTION MOTOR1
INDUCTION MOTOR1
 
gmrit-cse
gmrit-csegmrit-cse
gmrit-cse
 
Drives
DrivesDrives
Drives
 
Transformer
TransformerTransformer
Transformer
 

Último

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Último (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Matlab Mech Eee Lectures 1

  • 1. Motivation How it is useful for: Summary Introduction to MATLAB A Layman Approach P Bharani Chandra Kumar (bharani@aero.iitb.ac.in) Department of Electrical Engineering GMR Institute of Technology Rajam, AP Lecture series on MATLAB P Bharani Chandra Kumar
  • 2. Motivation How it is useful for: Summary Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 3. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 4. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 5. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 6. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 7. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 8. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 9. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 10. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB stands for MATrix LABoratory. Developed primarily by Cleve Moler in the 1970s. Need student access to Fortran subroutines for solving linear (LINPACK) and eigenvalue (EISPACK) problems without requiring knowledge of Fortran . Developed as an interactive system to access LINPACK and EISPACK. Gained popularity primarily through word of mouth In the 1980s, MATLAB was rewritten in C with more functionality Mathworks, Inc. was created in 1984 is now responsible for development, sale, and support for MATLAB P Bharani Chandra Kumar
  • 11. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 12. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements. P Bharani Chandra Kumar
  • 13. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements. P Bharani Chandra Kumar
  • 14. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements. P Bharani Chandra Kumar
  • 15. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements. P Bharani Chandra Kumar
  • 16. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is relatively easy to learn MATLAB code is optimized to be relatively quick when performing matrix operations MATLAB may behave like a calculator or as a programming language MATLAB is interpreted, errors are easier to fix Although primarily procedural, MATLAB does have some object-oriented elements. P Bharani Chandra Kumar
  • 17. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 18. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 19. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 20. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 21. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 22. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 23. Motivation History of MATLAB How it is useful for: Strengths of MATLAB Summary Weakness of MATLAB MATLAB is NOT a general purpose programming language MATLAB is an interpreted language (making it for the most part slower than a compiled language such as C++) MATLAB is designed for scientific computation and is not suitable for some things (such as parsing text) MATLAB is an interpreted language, slower than a compiled language such as C++ MATLAB commands are specific for MATLAB usage P Bharani Chandra Kumar
  • 24. Motivation Students How it is useful for: Engineers/ Scientists Summary Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 25. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for students: System dynamics can be analysed very easily Messy equations can be solved very easily Can enhance the skills required for present jobs Can do the projects in a very easy way Can be useful for analysis and study of multi-disciplinary research areas P Bharani Chandra Kumar
  • 26. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for students: System dynamics can be analysed very easily Messy equations can be solved very easily Can enhance the skills required for present jobs Can do the projects in a very easy way Can be useful for analysis and study of multi-disciplinary research areas P Bharani Chandra Kumar
  • 27. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for students: System dynamics can be analysed very easily Messy equations can be solved very easily Can enhance the skills required for present jobs Can do the projects in a very easy way Can be useful for analysis and study of multi-disciplinary research areas P Bharani Chandra Kumar
  • 28. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for students: System dynamics can be analysed very easily Messy equations can be solved very easily Can enhance the skills required for present jobs Can do the projects in a very easy way Can be useful for analysis and study of multi-disciplinary research areas P Bharani Chandra Kumar
  • 29. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for students: System dynamics can be analysed very easily Messy equations can be solved very easily Can enhance the skills required for present jobs Can do the projects in a very easy way Can be useful for analysis and study of multi-disciplinary research areas P Bharani Chandra Kumar
  • 30. Motivation Students How it is useful for: Engineers/ Scientists Summary Outline 1 Motivation History of MATLAB Strengths of MATLAB Weakness of MATLAB 2 How it is useful for: Students Engineers/ Scientists P Bharani Chandra Kumar
  • 31. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 32. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 33. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 34. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 35. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 36. Motivation Students How it is useful for: Engineers/ Scientists Summary How it is useful for Engineer/Scientists: Can do the research in various fields Contains various inbuilt blocks like electric power systems, IC engines, aircraft, process plant, etc . Need not required to struggle alot to get output as compared to other major packages Can compare the existing literature results using wide simulations Can be useful for analysis and study of multi-disciplinary research Can publish papers based on the simulations obtained P Bharani Chandra Kumar
  • 37. Motivation How it is useful for: Summary Summary General intro to MATLAB. History of MATLAB. Who and how it can be utilized! P Bharani Chandra Kumar
  • 38. Motivation How it is useful for: Summary Summary General intro to MATLAB. History of MATLAB. Who and how it can be utilized! P Bharani Chandra Kumar
  • 39. Motivation How it is useful for: Summary Summary General intro to MATLAB. History of MATLAB. Who and how it can be utilized! P Bharani Chandra Kumar
  • 40. Motivation How it is useful for: Summary Summary General intro to MATLAB. History of MATLAB. Who and how it can be utilized! P Bharani Chandra Kumar
  • 41. Appendix For Further Reading For Further Reading I Rudra Pratap. Started with MATLAB : A Quick intro for Scientists and Engineers. Oxford University Press, 2006. www.mathworks.com P Bharani Chandra Kumar
  • 42. Basics of MATLAB (Lecture 2) P Bharani Chandra Kumar bharani@aero.iitb.ac.in
  • 43. MATLAB GUI Command Window Workspace Command History bharani@aero.iitb.ac.in
  • 44. Desktop Tools Command Window type commands Workspace view program variables clear to clear double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary bharani@aero.iitb.ac.in
  • 45. Matrices • A vector x = [1 2 5 1] x = 1 2 5 1 • A matrix x = [1 2 3; 5 1 4; 3 2 -1] x = 1 2 3 5 1 4 3 2 -1 • Transpose y = x.’ y = 1 2 5 1 bharani@aero.iitb.ac.in
  • 46. Matrices (Contd…) Let, x= [ 1 2 3 5 1 4 3 2 -1] y = x(2,3) • x(i,j) subscription y = 4 • whole row y = x(3,:) y = 3 2 -1 y = x(:,2) • whole column y = 2 1 2 bharani@aero.iitb.ac.in
  • 47. Operators (Arithmetic) + addition - subtraction * multiplication .* element-by-element mult / division ./ element-by-element div ^ power .^ element-by-element power ‘ complex conjugate .‘ transpose transpose bharani@aero.iitb.ac.in
  • 48. Operators (Relational, Logical) == equal pi 3.14159265… ~= not equal j imaginary unit, −1 < less than i same as j <= less than or equal > greater than >= greater than or equal & AND | OR ~ NOT bharani@aero.iitb.ac.in
  • 49. Generating Vectors from functions x = zeros(1,3) • zeros(M,N) MxN matrix of zeros x = 0 0 0 • ones(M,N) MxN matrix of ones x = ones(1,3) x = 1 1 1 • rand(M,N) MxN matrix of uniformly x = rand(1,3) distributed random numbers on (0,1) x = 0.9501 0.2311 0.6068 bharani@aero.iitb.ac.in
  • 50. Operators (in general) [ ] concatenation x = [ zeros(1,3) ones(1,2) ] x = 0 0 0 1 1 ( ) subscription x = [ 1 3 5 7 9] x = 1 3 5 7 9 y = x(2) y = 3 y = x(2:4) y = 3 5 7 bharani@aero.iitb.ac.in
  • 51. MATRIX OPERATIONS Let, A = eye(3) >> A = [ 1 0 0 0 1 0 0 0 1 ] >> eig(A) >> inv(A) >>A' >>A*A ans = ans = ans = ans = 1 1 0 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 1 bharani@aero.iitb.ac.in
  • 52. MATRIX OPERATIONS (Contd…) Let, >> A = [1 2 3;4 5 6;7 8 9] A = [ 1 2 3 4 5 6 7 8 9 ] >> eig(A) >> B=A' >>C=A*B >> D=A.*B ans = B= C= D= 16.1168 1 4 7 14 32 50 1 8 21 -1.1168 2 5 8 32 77 122 8 25 48 -0.0000 3 6 9 50 122 194 21 48 81 bharani@aero.iitb.ac.in
  • 54. Applications of MATLAB (Lecture 3) P Bharani Chandra Kumar bharani@aero.iitb.ac.in
  • 55. Overview Linear algebra Solving a linear equation Finding eigenvalues and eigenvectors Curve fitting and interpolation Data analysis and statistics Nonlinear algebraic equations bharani@aero.iitb.ac.in
  • 56. Linear Algebra Solving a linear system Find the values of x, y and z for the following equations: 5x = 3y – 2z +10 8y +4z = 3x + 20 2x + 4y - 9z = 9 Step 1: Rearrange equations: 5x - 3y + 2z = 10 - 3x + 8y +4z = 20 2x + 4y - 9z = 9 Step 2: Write the equations in matrix form: [A] x = b  5 −3 2  10  A = − 3 8  4 b = 20   2  4 − 9  9   bharani@aero.iitb.ac.in
  • 57. Linear Algebra (Contd…) Step 3: Solve the matrix equation in MATLAB: >> A = [ 5 -3 2; -3 8 4; 2 4 -9]; >> b = [10; 20; 9] >> x = A b x = 3.442 3.1982 1.1868 % Veification >> c = A*x >> c = 10.0000 20.0000 9.0000 bharani@aero.iitb.ac.in
  • 58. Linear Algebra (Contd…) Finding eigenvalues and eigenvectors Eigenvalue problem in scientific computations shows up as: Av=λv The problem is to find ‘λ’ and ‘v’ for a given ‘A’ so that above eq. is satisfied: Method 1: Classical method by using pencil and paper: a) Finding eigenvalues from the determinant eqn. A − λI = 0 b) Sole for ‘n’ eigenvectors by substituting the corresponding eigenvalues in above eqn. bharani@aero.iitb.ac.in
  • 59. Linear Algebra (Contd…) Method 2: By using MATLAB: Step 1: Enter matrix A and type [V, D] = eig(A) >> A = [ 5 -3 2; -3 8 4; 2 4 -9]; >> [V, D] = eig(A) V = -0.1709 0.8729 0.4570 -0.2365 0.4139 -0.8791 0.9565 0.2583 -0.1357 D = -10.3463 0 0 0 4.1693 0 0 0 10.1770 bharani@aero.iitb.ac.in
  • 60. Linear Algebra (Contd…) Step 2: Extract what you need: ‘V’ is an ‘n x n’ matrix whose columns are eigenvectors D is an ‘n x n’ diagonal matrix that has the eigenvalues of ‘A’ on its diagonal. bharani@aero.iitb.ac.in
  • 61. Linear Algebra (Contd…) Cross check: Let us check 2nd eigenvalue and second eigenvector will satisfy A v = λ v or not: v2=V(:,2) % 2nd column of V v2 = 0.8729 0.4139 0.2583 >> lam2=D(2,2) % 2nd eigevalue lam2 = 4.1693 >> A*v2-lam2*v2 ans = 1.0e-014 * 0.0444 -0.1554 0.0888 bharani@aero.iitb.ac.in
  • 62. Curve Fitting What is curve fitting ? It is a technique of finding an algebraic relationship that “best” fits a given set of data. There is no magical function that can give you this relationship. You have to have an idea of what kind of relationship might exist between the input data (x) and output data (y). If you do not have a firm idea but you have data that you trust, MATLAB can help you to explore the best possible fit. bharani@aero.iitb.ac.in
  • 63. Curve Fitting (Contd…) Example 1 : straight line (linear) fit: x 5 10 20 50 100 Y 15 33 53 140 301 Step 1: Plot raw data: Enter the data in MATLAB and plot it: >> x = [ 5 10 20 50 100]; >> y = [15 33 53 140 301]; >> plot (x,y,’o’) >> grid bharani@aero.iitb.ac.in
  • 66. Curve Fitting (Contd…) Example 2 : Comparing different fits: x = 0: pi/30 : pi/3 y = sin(x) + rand (size(x))/100 Step 1: Plot raw data: >> plot (x,y,’o’) >> grid Step 2: Use basic fitting to do a quadratic and cubic fit Step 3 : Choose the best fit based on the residuals bharani@aero.iitb.ac.in
  • 68. Interpolation What is interpolation ? It is a technique of finding a functional relationship between variables such that a given set of discrete values of the variables satisfy that relationship. Usually, we get a finite set of data points from experiments. When we want to pass a smooth curve through these points or find some intermediate points, we use the technique of interpolation. Interpolation is NOT curve fitting, in that it requires the interpolated curve to pass through all the data points. Data can be interpolated using Splines or Hermite interpolants. bharani@aero.iitb.ac.in
  • 69. Interpolation (Contd…) MATLAB provides the following functions to facilitate interpolation: interp1 : One data interpolation i.e. given yi and xi, finds yj at desired xj from yj = f(xj). ynew = interp1(x,y,xnew, method) interp2 : Two dimensional data interpolation i.e. given zi at (xi,yi) from z = f(x,y). znew = interp2(x,y,z,xnew,ynew, method) interp3 : Three dimensional data interpolation i.e. given vi at (xi,yi,zi) from v = f(x,y,z). vnew = interp2(x,y,z,v,xnew,ynew,znew, method) spline : ynew = spline(x,y,xnew, method) bharani@aero.iitb.ac.in
  • 70. Interpolation (Contd…) Example: x = [1 2 3 4 5 6 7 8 9] y = [1 4 9 16 25 36 49 64 81] Find the value of 5.5? Method 1: Linear Interpolation MATLAB Command : >> yi=interp1(x,y,5.5,'linear') yi = 30.5000 bharani@aero.iitb.ac.in
  • 71. Interpolation (Contd…) Method 2: Cubic Interpolation MATLAB Command : >> yi = interp1(x,y,5.5,’cubic') yi = 30.2479 Method 3: Spline Interpolation MATLAB Command : >> yi = interp1(x,y,5.5,’spline') Note: 5.5*5.5= yi = 30.2500 bharani@aero.iitb.ac.in
  • 72. Data Analysis and statistics It includes various tasks, such as finding mean, median, standard deviation, etc. MATLAB provides an easy graphical interface to do such type of tasks. As a first step, you should plot your data in the form you wish. Then go to the figure window and select data statistics from the tools menu. Any of the statistical measures can be seen by checking the appropriate box. bharani@aero.iitb.ac.in
  • 73. Data Analysis and statistics (Contd…) Example: x = [1 2 3 4 5 6 7 8 9] y = [1 4 9 16 25 36 49 64 81] Find the minimum value, maximum value, mean, median? bharani@aero.iitb.ac.in
  • 74. Data Analysis and statistics (Contd…) bharani@aero.iitb.ac.in
  • 75. Data Analysis and statistics (Contd…) bharani@aero.iitb.ac.in
  • 76. Data Analysis and statistics (Contd…) bharani@aero.iitb.ac.in
  • 77. Data Analysis and statistics (Contd…) It can be performed directly by using MATLAB commands also: Consider: x = [1 2 3 4 5] mean (x) : Gives arithmetic mean of ‘x’ or the avg. data. MATLAB usage: mean (x) gives 3. median (x) : gives the middle value or arithmetic mean of two middle Numbers. MATLAB usage: median (x) gives 3. Std(x): gives the standard deviation Max(x)/min(x): gives the largest/smallest value bharani@aero.iitb.ac.in
  • 78. Solving nonlinear algebraic equations Step 1: Write the equation in the standard form: f(x) = 0 Step 2: Write a function that computes f(x). Step 3: Use the built-in function fzero to find the solution. Example 1: Solve sin x = e x − 5 Solution: x= fzero('sin(x)-exp(x)+5',1) x = 1.7878 bharani@aero.iitb.ac.in
  • 79. Solving nonlinear algebraic equations (contd…) • Example 2: Solve x2 − 2x + 4 = 0 Solution: x= fzero(‘x*x-2*x+4',1) x x=e sin = x −5 1.7878 bharani@aero.iitb.ac.in
  • 81. Optimization Techniques through MATLAB (Lecture 4) P Bharani Chandra Kumar bharani@aero.iitb.ac.in
  • 82. Overview Unconstrained Optimization Constrained Optimization Constrained Optimization through gradients bharani@aero.iitb.ac.in
  • 83. Why Optimize! Engineers are always interested in finding the ‘best’ solution to the problem at hand Fastest Fuel Efficient Optimization theory allows engineers to accomplish this Often the solution may not be easily obtained In the past, it has been surrounded by certain mistakes bharani@aero.iitb.ac.in
  • 84. The Greeks started it! Queen Dido of Carthage (7 century BC) – Daughter of the king of Tyre – Agreed to buy as much land as she could “enclose with one bull’s hide” – Set out to choose the largest amount of land possible, with one border along the sea • A semi-circle with side touching the ocean • Founded Carthage – Fell in love with Aeneas but committed suicide when he left. bharani@aero.iitb.ac.in
  • 85. The Italians Countered Joseph Louis Lagrange (1736-1813) His work Mécanique Analytique (Analytical Mechanics) (1788) was a mathematical masterpiece Invented the method of ‘variations’ which impressed Euler and became ‘calculus of variations’ Invented the method of multipliers (Lagrange multipliers) Sensitivities of the performance index to changes in states/constraints Became the ‘father’ of ‘Lagrangian’ Dynamics Euler-Lagrange Equations bharani@aero.iitb.ac.in
  • 86. The Multi-Talented Mr. Euler Euler (1707-1783) Friend of Lagrange Published a treatise which became the de facto standard of the ‘calculus of variations’ The Method of Finding Curves that Show Some Property of Maximum or Minimum He solved the brachistachrone (brachistos = shortest, chronos = time) problem very easily Minimum time path for a bead on a string, Cycloid bharani@aero.iitb.ac.in
  • 87. Hamilton and Jacobi William Hamilton (1805-1865) Inventor of the quaternion Karl Gustav Jacob Jacobi (1804- 1851) Discovered ‘conjugate points’ in the fields of extremals Gave an insightful treatment to the second variation Jacobi criticized Hamilton’s work Hamilton-Jacobi equation Became the basis of Bellman’s work 100 years later bharani@aero.iitb.ac.in
  • 88. What to Optimize? Engineers intuitively know what they are interested in optimizing Straightforward problems Fuel Time Power Effort More complex Maximum margin Minimum risk The mathematical quantity we optimize is called a cost function or performance index bharani@aero.iitb.ac.in
  • 89. Optimization through MATLAB Consider initially the problem of finding a minimum to the function: MATLAB function FMINCON solves problems of the form: min F(X) subject to: A*X <= B, Aeq*X = Beq (linear constraints) C(X) <= 0, Ceq(X) = 0 (nonlinear constraints) LB <= X <= UB bharani@aero.iitb.ac.in
  • 90. Optimization through MATLAB (Contd…) X = FMINCON(FUN,X0,A,B) starts at X0 and finds a minimum X to the function FUN, subject to the linear inequalities A*X <= B. X=FMINCON(FUN,X0,A,B,Aeq,Beq) minimizes FUN subject to the linear equalities: Aeq*X = Beq as well as A*X <= B. (Set A=[ ] and B=[ ] if no inequalities exist.) bharani@aero.iitb.ac.in
  • 91. Optimization through MATLAB (Contd…) X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB) defines a set of lower and upper bounds on the design variables, X, so that the solution is in the range LB <= X <= UB. Use empty matrices for LB and UB if no bounds exist. Set LB(i) = -Inf if X(i) is unbounded below; and set UB(i) = Inf if X(i) is unbounded above. X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON) subjects the minimization to the constraints defined in NONLCON. The function NONLCON accepts X and returns the vectors C and Ceq, representing the nonlinear inequalities and equalities respectively. bharani@aero.iitb.ac.in
  • 92. Unonstrained Optimization : Example Consider the above problem with no constraints: f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1) Solution by MATLAB: Step 1: Create an inline object of the function to be minimized fun = inline('exp(x(1)) * (4*x(1)^2 + 2*x(2)^2 + 4*x(1)*x(2) + 2*x(2) + 1)'); Step 2: Take a guess at the solution: x0 = [-1 1]; Step 3: Solve using fminunc function: [x, fval] = fminunc(fun, x0); bharani@aero.iitb.ac.in
  • 93. Unconstrained Optimization : Example (Contd…) >> x = 0.5000 -1.0000 >> fval = 1.3028e-010 bharani@aero.iitb.ac.in
  • 94. Constrained Optimization : Example Consider initially the problem of finding a minimum to the function: f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1) Subjected to: 1.5 + x(1).x(2) - x(1) - x(2) < = 0 - x(1).x(2) < = 10 bharani@aero.iitb.ac.in
  • 95. Constrained Optimization : Example (contd…) Solution using MATLAB: Step 1: Write the m-file for objective function: function f = objfun(x) % objective function f=exp(x(1)) * (4*x(1)^2 + 2*x(2)^2 + 4*x(1)*x(2) + 2*x(2) + 1); Step 2: Write the m-file for constraints: function [c, ceq] = confun(x) % Nonlinear inequality constraints: c = [1.5 + x(1)*x(2) - x(1) - x(2); -x(1)*x(2) - 10]; % no nonlinear equality constraints: ceq = []; bharani@aero.iitb.ac.in
  • 96. Constrained Optimization : Example (contd…) Step 3: Take a guess at the solution x0 = [-1 1]; options = optimset('LargeScale','off','Display','iter'); % We have no linear equalities or inequalities or bounds, % so pass [] for those arguments [x,fval,exitflag,output] = fmincon('objfun',x0,[],[],[],[],[],[],'confun',options) ; bharani@aero.iitb.ac.in
  • 97. max Directional Iter F-count f(x) constraint Step-size derivative Procedure 1 3 1.8394 0.5 1 0.0486 2 7 1.85127 -0.09197 1 -0.556 Hessian modified twice 3 11 0.300167 9.33 1 0.17 4 15 0.529834 0.9209 1 -0.965 5 20 0.186965 -1.517 0.5 -0.168 6 24 0.0729085 0.3313 1 -0.0518 7 28 0.0353322 -0.03303 1 -0.0142 8 32 0.0235566 0.003184 1 -6.22e-006 9 36 0.0235504 9.032e-008 1 1.76e-010 Hessian modified Optimization terminated successfully: % A solution to this problem has been found at: x x = -9.5474 1.0474 bharani@aero.iitb.ac.in
  • 98. % The function value at the solution is: fval fval = 0.0236 % Both the constraints are active at the solution: [c, ceq] = confun(x) c = 1.0e-014 * 0.1110 -0.1776 ceq = [] bharani@aero.iitb.ac.in
  • 100. System Identification (Lecture 5) P Bharani Chandra Kumar bharani@aero.iitb.ac.in
  • 101. Overview Introduction Basic questions about system identification Common terms used in system identification Basic information about dynamical systems Basic steps for system identification An exciting example bharani@aero.iitb.ac.in
  • 102. Introduction What is system identification? Water Can you Say Heater What is this! Cold Water Hot Water bharani@aero.iitb.ac.in
  • 103. What is system identification? Determining system dynamics from input-output data Generate enough data for estimation and validation Select range for estimation and validation Select order of the system Check for best fit and determine the system dynamics bharani@aero.iitb.ac.in
  • 104. Basic questions about system identification What is system identification? It enables you to build mathematical models of a dynamic system based on measured data. You adjust the parameters of a given model until its output coincides as well as possible with the measured output. How do you know if the model is any good? A good test is to compare the output of the model to measured data that was not used for the fit. bharani@aero.iitb.ac.in
  • 105. Basic questions about system identification (contd…) What models are most common? The most common models are difference-equation descriptions, such as ARX and ARMAX models, as well as all types of linear state-space models. • Do you have to assume a model of a particular type? For parametric models, you specify the model structure. This can be as easy as selecting a single integer -- the model order -- or it can involve several choices. bharani@aero.iitb.ac.in
  • 106. Basic questions about system identification (contd…) What does the System Identification Toolbox contain? It contains all the common techniques used to adjust parameters in all kinds of linear models. • How do I get started? If you are a beginner, browse through The Graphical User Interface. Use the graphical user interface (GUI) and check out the built-in help functions. bharani@aero.iitb.ac.in
  • 107. Basic questions about system identification (contd…) Is this really all there is to system identification? There is a great deal written on the subject of system identification. However, the best way to explore system identification is by working with real data. It is important to remember that any estimated model, no matter how good it looks on your screen, is only a simplified reflection of reality. bharani@aero.iitb.ac.in
  • 108. Common terms used in system identification Estimation data: The data set that is used to create a model of the data. Validation data: The data set (different from estimation data) that is used to validate the model. Model views: The various ways of inspecting the properties of a model, such as zeros and poles, as well as transient and frequency responses. bharani@aero.iitb.ac.in
  • 109. Common terms used in system identification (contd…) Model sets or model structures are families of models with adjustable parameters. Parameter estimation is the process of finding the "best" values of these adjustable parameters. The system identification problem is to find both the model structure and good numerical values of the model parameters. bharani@aero.iitb.ac.in
  • 110. Common terms used in system identification (contd…) • This is a matter of using numerical search to find those numerical values of the parameters that give the best agreement between the model's (simulated or predicted) output and the measured output. • Nonparametric identification methods: Techniques to estimate model behavior without necessarily using a given parameterized model set. • Model validation is the process of gaining confidence in a model. bharani@aero.iitb.ac.in
  • 111. Basic information about dynamical systems bharani@aero.iitb.ac.in
  • 112. Basic Steps for System Identification Import data from the MATLAB workspace. Plot the data using Data Views. Preprocess the data using commands in the Preprocess menu. For example, you can remove constant offsets or linear trends (for linear models only), filter data, or select regions of interest. bharani@aero.iitb.ac.in
  • 113. Basic Steps for System Identification (contd…) Select estimation and validation data. Estimate models using commands in the Estimate menu. Validate models using Models Views. Export models to the MATLAB workspace for further processing . bharani@aero.iitb.ac.in
  • 115. Solution of Ordinary Differential Equations and Engineering Computing (Lecture 6) P Bharani Chandra Kumar bharani@aero.iitb.ac.in
  • 116. Solution of Ordinary Differential Equaions bharani@aero.iitb.ac.in
  • 117. Overview Introduction Examples bharani@aero.iitb.ac.in
  • 118. Introduction DSOLVE Symbolic solution of ordinary differential equations. DSOLVE('eqn1','eqn2', ...) accepts symbolic equations representing ordinary differential equations and initial conditions. Several equations or initial conditions may be grouped together, separated by commas, in a single input argument. By default, the independent variable is 't'. The independent variable may be changed from 't' to some other symbolic variable by including that variable as the last input argument. bharani@aero.iitb.ac.in
  • 119. Introduction (contd…) The letter 'D' denotes differentiation with respect to the independent variable, i.e. usually d/dt. A "D" followed by a digit denotes repeated differentiation; e.g., D2 is d^2/dt^2. Any characters immediately following these differentiation operators are taken to be the dependent variables; e.g., D3y denotes the third derivative of y(t). Note that the names of symbolic variables should not contain the letter "D". bharani@aero.iitb.ac.in
  • 120. Introduction (contd…) Initial conditions are specified by equations like 'y(a)=b' or 'Dy(a) = b' where y is one of the dependent variables and a and b are constants. If the number of initial conditions given is less than the number of dependent variables, the resulting solutions will obtain arbitrary constants, C1, C2, etc. Three different types of output are possible. For one equation and one output, the resulting solution is returned, with multiple solutions to a nonlinear equation in a symbolic vector. bharani@aero.iitb.ac.in
  • 121. Introduction (contd…) If no closed-form (explicit) solution is found, an implicit solution is attempted. When an implicit solution is returned, a warning is given. If neither an explicit nor implicit solution can be computed, then a warning is given and the empty sym is returned. In some cases concerning nonlinear equations, the output will be an equivalent lower order differential equation or an integral. bharani@aero.iitb.ac.in
  • 122. Examples 1) dsolve('Dx = -a*x') returns ans: exp(-a*t)*C1 2) x = dsolve('Dx = -a*x','x(0) = 1','s') returns ans: x = exp(-a*s) 3) y = dsolve('(Dy)^2 + y^2 = 1','y(0) = 0') returns ans: y= [ sin(t)] [ -sin(t)] bharani@aero.iitb.ac.in
  • 123. Examples (contd…) 4) S = dsolve('Df = f + g','Dg = -f + g','f(0) = 1','g(0) = 2') Ans: S.f = exp(t)*cos(t)+2*exp(t)*sin(t) S.g = -exp(t)*sin(t)+2*exp(t)*cos(t) 5) dsolve('Df = f + sin(t)', 'f(pi/2) = 0') Ans: -1/2*cos(t)- 1/2*sin(t)+1/2*exp(t)/(cosh(1/2*pi)+ sinh(1/2*pi)) bharani@aero.iitb.ac.in
  • 125. Outline of lecture MATLAB as a calculator revisited Concept of M-files Decision making in MATLAB Use of IF and ELSEIF commands Example: Real roots of a quadratic bharani@aero.iitb.ac.in
  • 126. MATLAB as a calculator MATLAB can be used as a ‘clever’ calculator This has very limited value in engineering Real value of MATLAB is in programming Want to store a set of instructions Want to run these instructions sequentially Want the ability to input data and output results Want to be able to plot results Want to be able to ‘make decisions’ bharani@aero.iitb.ac.in
  • 127. Example n 1 1 1 1 y=∑ = + + + ... i =1 i 1 2 3 Can do using MATLAB as a calculator >> x = 1:10; >> term = 1./sqrt(x); >> y = sum(term); Far easier to write as an M-file bharani@aero.iitb.ac.in
  • 128. How to write an M-file File → New → M-file Takes you into the file editor Enter lines of code (nothing happens) Save file (we will call ours bharani.m) Run file Edit (ie modify) file if necessary bharani@aero.iitb.ac.in
  • 129. Bharani.m Version 1 n = input(‘Enter the upper limit: ‘); x = 1:n; % Matlab is case sensitive term = sqrt(x); y = sum(term) What happens if n < 1 ? bharani@aero.iitb.ac.in
  • 130. Bharani.m Version 2 n = input(‘Enter the upper limit: ‘); if n < 1 disp (‘Your answer is meaningless!’) end x = 1:n; term = sqrt(x); Jump to here if TRUE y = sum(term) Jump to here if FALSE bharani@aero.iitb.ac.in
  • 131. Decision making in MATLAB For ‘simple’ decisions? IF … END (as in last example) More complex decisions? IF … ELSEIF … ELSE ... END Example: Real roots of a quadratic equation bharani@aero.iitb.ac.in
  • 132. Roots of ax2+bx+c=0 Roots set by discriminant − b ± b 2 − 4ac ∆ < 0 (no real roots) x= 2a ∆ = 0 (one real root) ∆ > 0 (two real roots) 2 MATLAB needs to make ∆ = b − 4ac decisions (based on ∆) bharani@aero.iitb.ac.in
  • 133. One possible M-file Read in values of a, b, c Calculate ∆ IF ∆ < 0 Print message ‘ No real roots’→ Go END ELSEIF ∆ = 0 Print message ‘One real root’→ Go END ELSE Print message ‘Two real roots’ END bharani@aero.iitb.ac.in
  • 134. M-file (bharani.m) %================================================ % Demonstration of an m-file % Calculate the real roots of a quadratic equation %================================================ clear all; % clear all variables clc; % clear screen coeffts = input('Enter values for a,b,c (as a vector): '); % Read in equation coefficients a = coeffts(1); b = coeffts(2); c = coeffts(3); delta = b^2 - 4*a*c; % Calculate discriminant bharani@aero.iitb.ac.in
  • 135. M-file (bharani.m) (contd…) % Calculate number (and value) of real roots if delta < 0 fprintf('nEquation has no real roots:nn') disp(['discriminant = ', num2str(delta)]) elseif delta == 0 fprintf('nEquation has one real root:n') xone = -b/(2*a) else fprintf('nEquation has two real roots:n') x(1) = (-b + sqrt(delta))/(2*a); x(2) = (-b – sqrt(delta))/(2*a); fprintf('n First root = %10.2ent Second root = %10.2f', x(1),x(2)) end bharani@aero.iitb.ac.in
  • 136. Conclusions MATLAB is more than a calculator its a powerful programming environment • Have reviewed: – Concept of an M-file – Decision making in MATLAB – IF … END and IF … ELSEIF … ELSE … END – Example of real roots for quadratic equation bharani@aero.iitb.ac.in
  • 138. Graphics By G Satish
  • 139. Outline 2-D plots 3-D plots Handle objects
  • 141. Simple plot >> a=[1 2 3 4] >> plot(a)
  • 142. Overlay plots using plot command >> t=0:pi/10:2*pi; >> y=sin(t); z=cos(t); >> plot(t,y,t,z)
  • 143. Overlay plots(contd…) using hold command >> plot(t,sin(t)); >> grid >> hold >> plot(t,sin(t))
  • 144. Overlay plots(contd..) using line command >> t=linspace(0,2*pi,10) >> y=sin(t); y2=t; y3=(t.^3)/6+(t.^5)/120; >> plot(t,y1) >> line(t,y2,’linestyle’,’--’) >> line(t,y3,’marker’,’o’)
  • 146. Style options >> t=0:pi/10:2*pi; >> y=sin(t); z=cos(t); >>plot(t,y,’go-’,t,z,’b*--’)
  • 147.
  • 148. Style options b blue . point - solid g green o circle : dotted r red x x-mark -. dashdot c cyan + plus -- dashed m magenta * star y yellow s square k black d diamond v triangle (down) ^ triangle (up) < triangle (left) > triangle (right) p pentagram h hexagram
  • 149. Labels, title, legend and other text objects >> a=[1 2 3 4]; b=[ 1 2 3 4]; c=[4 5 6 7] >> plot(a,b,a,c) >> grid >> xlabel(‘xaxis’) >> ylabel(‘yaxis’) >> title(‘example’) >> legend(‘first’,’second’) >> text(2,6,’plot’)
  • 150. Modifying plots with the plot editor To activate this tool go to figure window and click on the left-leaning arrow Now you can select and double click on any object in the current plot to edit it. Double clicking on the selected object brings up a property editor window where you can select and modify the current properties of the object
  • 151. Subplots >> t=linspace(0,2*pi,10); y=sin(t); z=cos(t); >> figure >> subplot(2,1,1) >> subplot(2,1,2) >> subplot(2,1,1); plot(t,y) >> subplot(2,1,2); plot(t,z)
  • 152.
  • 153. Logarthmic plots >> x=0:0.1:2*pi; >>subplot(2,2,1) >> semilogx(x,exp(-x)); >> grid >> subplot(2,2,2) >> semilogy(a,b); >> grid >> subplot(2,2,3) >> loglog(x,exp(-x)); >> grid
  • 154. Zoom in and zoom out >> figure >> plot(t,sin(t)) >> axis([0 2 -2 2])
  • 155.
  • 156. Specialised plotting routines >> stem(t,sin(t)); >> bar(t,sin(t)) >> a=[1 2 3 4]; stairs(a);
  • 158. Simple 3-D plot Plot of a parametric space curve >> t=linspace(0,1,100); >> x=t; y=t; z=t.^3; >> plot3(x,y,z); grid
  • 159. View >> t=linspace(0,6*pi,100); >> x=cos(t); y=sin(t); z=t; >> subplot(2,2,1); plot3(x,y,z); >> subplot(2,2,2); plot3(x,y,z); view(0,90); >> subplot(2,2,3); plot3(x,y,z); view(0,0); >> subplot(2,2,4); plot3(x,y,z); view(90,0);
  • 161. Mesh plots >> x=linspace(-3,3,50); >> [X,Y]= meshgrid(x,y); >> Z=X.*Y.*(X.^2-Y.^2)./(X.^2+Y.^2); >> mesh(X,Y,Z); >> figure(2)
  • 163. Surface plots >> u = -5 : 0.2 : 5; >> [X,Y] = meshgrid(u,u); >> Z=cos(X).*cos(Y).*exp(-sqrt(X.^2+Y.^2)/4); >> surf(X,Y,Z)
  • 166. Handle Graphics Objects Handle Graphics is an object-oriented structure for creating, manipulating and displaying graphics Graphics in Matlab consist of objects Every graphics objects has: – a unique identifier, called handle – a set of characteristics, called properties
  • 167. Getting object handles There are two ways for getting object handles • By creating handles explicitly at the object- creation level commands • By using explicit handle return functions
  • 168. Getting object handles By creating handles explicitly at the object- creation level commands >> hfig=figure >> haxes=axes(‘position’,[0.1 0.1 0.4 0.4]) >> t=linspace(0,pi,10); >> hL = line(t,sin(t)) >> hx1 = xlabel(‘Angle’)
  • 169. Getting object handles By using explicit handle return functions >> gcf gets the handle of the current figure >> gca gets handle of current axes >> gco returns the current object in the current figure
  • 170. Getting object handles Example >> figure >> axes >> line([1 2 3 4],[1 2 3 4]) >> hfig = gcf >> haxes = gca Click on the line in figure >>hL=gco
  • 171. Getting properties of objects The function ‘get’ is used to get a property value of an object specified by its handle get(handle,’PropertyName’) The following command will get a list of all property names and their current values of an object with handle h get(h)
  • 172. Getting properties of objects Example >> h1=plot([ 1 2 3 4]);returns a line object >> get(h1) >> get(h1,’type’) >> get(h1,’linestyle’)
  • 173. Setting properties of objects The properties of the objects can be set by using ‘set’ command which has the following command form Set(handle, ‘PropertyName’,Propertyvalue’) By using following command you can see the the list of properties and their values Set(handle)
  • 174. Setting properties of objects example >> t=linspace(0,pi,50); >> x=t.*sin(t); >> hL=line(t,x);
  • 175. Setting properties of objects >> set(hL,’linestyle’,’--’);
  • 176. Setting properties of objects >> set(hL,’linewidth’,3,’marker’,’o’)
  • 177. Setting properties of objects >> yvec = get(hL,’ydata’); >> yvec(15:20) = 0; >> yvec(40:45) = 0; >> set(hL, ’ydata’, yvec)
  • 178. Creating subplots using axes command >> hfig=figure >> ha1=axes(‘position’,[0.1 0.5 0.3 0.3]) >> line([1 2 3 4],[1 2 3 4]) >> ha2=axes(‘position’[0.5 0.5 0.3 0.3]) >> line([1 2 3 4],[ 1 10 100 1000]) >> ha3=axes(‘position’,[0.1 0.1 0.3 0.3]) >> line([1 2 3 4],[0.1 0.2 0.3 0.4]) >> ha4=axes(‘position’,[0.5 0.1 0.3 0.3]) >> line([1 2 3 4],[10 10 10 10])