SlideShare a Scribd company logo
An Introduction to MATLAB




Santosh K Venu                 1
What is MATLAB?


• MATLAB
  – MATrix LABoratory: MATLAB is a program for doing numerical
    computation. It was originally designed for solving linear algebra
    type problems using matrices. It’s name is derived from MATrix
    LABoratory.
  – MATLAB has since been expanded and now has built-in
    functions for solving problems requiring data analysis, signal
    processing, optimization, and several other types of scientific
    computations. It also contains functions for 2-D and 3-D
    graphics and animation.



                                                                      2
•   Stands for MATrix LABoratory
•   Interpreted language
•   Scientific programming environment
•   Very good tool for the manipulation of matrices
•   Great visualisation capabilities
•   Loads of built-in functions
•   Easy to learn and simple to use


                                                      3
MATLAB Overview



• Strengths of MATLAB
• Weaknesses of MATLAB




                         4
Strengths 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




                                                5
Weaknesses 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, C++)
• MATLAB is designed for scientific computation and is
  not suitable for some things (such as design an interface)




                                                           6
Matlab Desktop

• Command Window
   – type commands
• Workspace
   – view program variables
   – clear to clear
       • clear all: removes all variables, globals, functions and MEX
         links
       • clc: clear command window
   – double click on a variable to see it in the Array Editor
• Command History
   – view past commands
• Launch Pad
   – access help, tools, demos and documentation
                                                                        7
Matlab Desktop - con’t

                                 Launch Pad




                               Workspace


 Current
DIrectory
               Command
                Window                History




                                                8
How to Resume Default Desktop




                                9
Matlab Help


• Different ways to find information
   – help
   – help general, help mean, sqrt...
   – helpdesk - an html document with links to further
     information




                                                         10
Matlab Help - con’t




                      11
Matlab Help - con’t




                      12
Command window

•       The MATLAB environment is command oriented somewhat like
        UNIX. A prompt (>>) appears on the screen and a MATLAB
        statement can be entered. When the <ENTER> key is pressed, the
        statement is executed, and another prompt appears.
•       If a statement is terminated with a semicolon ( ; ), no results will be
        displayed. Otherwise results will appear before the next prompt.

    » a=5;
    » b=a/2

    b=

        2.5000

    »
                                                                                  13
MATLAB Special Variables


ans       Default variable name for results
pi        Value of 
inf       Infinity
NaN       Not a number          e.g. 0/0
i and j   i = j = square root of minus one: (-1) (imaginary number)
          e.g. sqrt(-1)       ans= 0 + 1.0000i
realmin   The smallest usable positive real number
realmax   The largest usable positive real number




                                                               14
Variables
• No need for types. i.e.,

        int a;
        double b;
        float c;
• All variables are created with double precision unless
  specified and they are matrices.
        Example:
        >>x=5;
        >>x1=2;
• After these statements, the variables are 1x1 matrices with
  double precision
Working with Matrices and Arrays


• Since Matlab makes extensive use of matrices, the best
  way for you to get started with MATLAB is to learn how
  to handle matrices.
   – Separate the elements of a row with blanks or commas.
   – Use a semicolon ; to indicate the end of each row.
   – Surround the entire list of elements with square brackets, [ ].


       A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays the matrix you just entered:
  A=
       16   3    2     13
       5    10   11    8
       9    6     7    12
       4    15    14   1

• Once you have entered the matrix, it is automatically
  remembered in the MATLAB workspace. You can
  simply refer to it as A.

• Keep in mind, variable names are case-sensitive
Manipulating Matrices
                                                   A=
                                                   16 3   2     13
                                                   5 10   11    8
• Access elements of a matrix                      9 6     7    12
>>A(1,2)                                           4 15    14   1

ans=
3                indices of matrix element(s)
• Remember Matrix(row,column)
• Naming convention Matrix variables start with a capital
  letter while vectors or scalar variables start with a simple
  letter



                               18
MATLAB Relational Operators

• MATLAB supports six relational operators.

  Less Than                   <
  Less Than or Equal          <=
  Greater Than                >
  Greater Than or Equal       >=
  Equal To                    ==
  Not Equal To                ~=




                                              19
MATLAB Logical Operators



• MATLAB supports three logical operators.

  not          ~      % highest precedence
  and          &      % equal precedence with or
  or           |      % equal precedence with and




                                                    20
MATLAB Matrices


• MATLAB treats all variables as matrices. For our
  purposes a matrix can be thought of as an array, in fact,
  that is how it is stored.

• Vectors are special forms of matrices and contain only one
  row OR one column.

• Scalars (1,1)are matrices with only one row AND one
  column


                                                              21
MATLAB Matrices


• A matrix with only one row AND one column is a scalar.
  A scalar can be created in MATLAB as follows:

» a=23

a=

  23


                                                           22
MATLAB Matrices


• A matrix with only one row is called a row vector. A row
  vector can be created in MATLAB as follows (note the
  commas):

» rowvec = [12 , 14 , 63] or rowvec = [12 14 63]

rowvec =

  12   14   63

                                                         23
MATLAB Matrices

• A matrix with only one column is called a column vector. A
  column vector can be created in MATLAB as follows (note
  the semicolons):

» colvec = [13 ; 45 ; -2]

colvec =

  13
  45
  -2


                                                          24
MATLAB Matrices

• A matrix can be created in MATLAB as follows (note the
  commas AND semicolons):

» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

   1    2    3
   4    5    6
   7    8    9

                                                           25
Extracting a Sub-Matrix

• A portion of a matrix can be extracted and stored in a smaller
  matrix by specifying the names of both matrices, the rows and
  columns. The syntax is:

      sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;

  where r1 and r2 specify the beginning and ending rows and c1
  and c2 specify the beginning and ending columns to be
  extracted to make the new matrix.



                                                             26
MATLAB Matrices

•   A column vector can be        •   Here we extract column 2 of
    extracted from a matrix. As       the matrix and make a
    an example we create a            column vector:
    matrix below:

» matrix=[1,2,3;4,5,6;7,8,9]      » col_two=matrix( : , 2)

matrix =                          col_two =
  1 2      3                         2
  4 5      6                         5
  7 8      9                         8



                                                                    27
MATLAB Matrices

•   A row vector can be extracted   •   Here we extract row 2 of the
    from a matrix. As an example        matrix and make a row vector.
    we create a matrix below:           Note that the 2:2 specifies the
                                        second row and the 1:3
» matrix=[1,2,3;4,5,6;7,8,9]            specifies which columns of the
                                        row.
matrix =
                                    » rowvec=matrix(2 : 2 , 1 : 3)
    1   2   3
    4   5   6                       rowvec =
    7   8   9

                                        4   5   6


                                                                          28
Matrices transpose

•   a vector        x = [1 2 5 1]

    x =
          1     2    5   1




•   transpose       y = x’          y =
                                          1
                                          2
                                          5
                                          1
                                              29
Scalar - Matrix Addition

» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
   1 2 3
   4 5 6
» c= b+a          % Add a to each element of b
c=
   4 5 6
   7 8 9


                                                 30
Scalar - Matrix Subtraction

» a=3;
» b=[1, 2, 3;4, 5, 6]
b=
    1 2 3
    4 5 6
» c = b - a %Subtract a from each element of b
c=
   -2 -1 0
    1 2 3

                                                 31
Scalar - Matrix Multiplication


» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
    1 2 3
    4 5 6
» c = a * b % Multiply each element of b by a
c=
    3 6 9
   12 15 18
                                                32
Scalar - Matrix Division


» a=3;
» b=[1, 2, 3; 4, 5, 6]
b=
    1 2 3
    4 5 6
» c = b / a % Divide each element of b by a
c=
   0.3333 0.6667 1.0000
   1.3333 1.6667 2.0000
                                              33
Math & Assignment Operators

Power             ^    or .^   a^b   or     a.^b
Multiplication    *    or .*   a*b   or     a.*b
Division          /    or ./   a/b   or     a./b




 - (unary) + (unary)
 Addition      +           a+b
 Subtraction -             a-b
 Assignment =                    a=b      (assign b to a)
                                                            34
Other operators


[ ] 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                35
The : operator


• VERY important operator in Matlab
• Means ‘to’
>> 1:10
ans =
   1 2 3 4 5 6 7 8 9 10
>> 1:2:10
                                    Try the following
ans =                               >> x=0:pi/12:2*pi;
                                    >> y=sin(x)
   1 3 5 7 9
Introduction to Matlab           36
Sumitha Balasuriya
•   Length
•   Max
•   Mean
•   Median
•   Min
•   Prod
•   Size
•   Var
•   Sum
•   Det
•   Rank
•   Eig
•   sort/flipr   37
Matlab Graphics


x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2pi')
ylabel('Sine of x')
title('Plot of the
  Sine Function')




                                38
Multiple Graphs


t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on




                                 39
• Plotting Multiple Data Sets in One Graph
   – Multiple x-y pair arguments create multiple graphs with a
     single call to plot.
  For example:         x = 0:pi/100:2*pi;
                     y = sin(x);
                     y2 = sin(x-.25);
                     y3 = sin(x-.5);
                     plot(x,y,x,y2,x,y3)
Multiple Plots


t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)




                                 41
Graph Functions (summary)


•   plot      linear plot
•   stem      discrete plot
•   grid      add grid lines
•   xlabel    add X-axis label
•   ylabel    add Y-axis label
•   title     add graph title
•   subplot   divide figure window
•   figure    create new figure window
•   pause     wait for user response

                                         42
Some Useful MATLAB commands


•   who         List known variables
•   whos        List known variables plus their size
•   help        >> help sqrt    Help on using sqrt
•   lookfor     >> lookfor sqrt
                Search for keyword sqrt in on MATLABPATH.
•   what        >> what ('directory')
                List MATLAB files in directory
•   clear       Clear all variables from work space
•   clear x y   Clear variables x and y from work space
•   clc         Clear the command window

                                                          43
Flow Control

•   if
•   for
•   while
•   break
•   ….
Control Structures
                          Some Dummy Examples
• If Statement Syntax
                          if ((a>3) & (b==5))
                               Some Matlab Commands;
if (Condition_1)          end
        Matlab Commands   if (a<3)
elseif (Condition_2)           Some Matlab Commands;
                          elseif (b~=5)
        Matlab Commands        Some Matlab Commands;
elseif (Condition_3)      end
        Matlab Commands
                          if (a<3)
else                           Some Matlab Commands;
        Matlab Commands   else
                               Some Matlab Commands;
end                       end
Control Structures
                       Some Dummy Examples

                       for i=1:100
• For loop syntax      end
                           Some Matlab Commands;


                       for j=1:3:200
for i=Index_Array          Some Matlab Commands;
   Matlab Commands     end

end                    for m=13:-0.2:-21
                           Some Matlab Commands;
                       end

                       for k=[0.1 0.3 -13 12 7 -9.3]
                           Some Matlab Commands;
                       end
Control Structures


• While Loop Syntax
                       Dummy Example
while (condition)
                       while ((a>3) & (b==5))
  Matlab Commands
                          Some Matlab Commands;
end                    end
Classification of flow
%|-------------------------------------|
This function classifies a flow |
according to the values of the Reynolds (Re) and Mach (Ma). |
Re <= 2000, laminar flow
2000 < Re <= 5000, transitional flow
Re > 5000, turbulent flow
Ma < 1, sub-sonic flow
Ma = 1, sonic flow
Ma > 1, super-sonic flow
%|-------------------------------------|




                                                                48
Vector Function


Consider now a vector function f(x) = [f1(x1,x2,x3) f2(x1,x2,x3)
f3(x1,x2,x3)]T, where x =
[x1,x2,x3]T (The symbol []T indicates the transpose of a matrix).
Specifically,
f1(x1,x2,x3) = x1 cos(x2) + x2 cos(x1) + x3
f2(x1,x2,x3) = x1x2 + x2x3 + x3x1
f3(x1,x2,x3) = x1
2 + 2x1x2x3 + x3
2
A function to evaluate the vector function f(x) is shown below.
                                                                49
Summation

%Check if m or n are matrices
if length(n)>1 | length(m)>1 then
error('sum2 - n,m must be scalar values')
abort
end
%Calculate summation if n and m are scalars
S = 0; %initialize sum
for i = 1:n                %sweep by index i
for j = 1:m                %sweep by index j
S = S + 1/((i+j)^2+1);
end
end
                                                   50
Thank U

          51

More Related Content

PPTX
Seminar on MATLAB
PPT
Introduction to Matlab
PPTX
Matlab plotting
PPTX
Matlab ploting
PPT
Matlab practical and lab session
PPT
Introduction to matlab
PPTX
MATLAB - Arrays and Matrices
PPT
Brief Introduction to Matlab
Seminar on MATLAB
Introduction to Matlab
Matlab plotting
Matlab ploting
Matlab practical and lab session
Introduction to matlab
MATLAB - Arrays and Matrices
Brief Introduction to Matlab

What's hot (20)

PPTX
Matlab ppt
PPT
Introduction to matlab
PPTX
Basic matlab and matrix
PDF
Matlab intro
PPTX
Matlab Introduction
PDF
MATLAB INTRODUCTION
PPSX
Matlab basic and image
PPTX
An Introduction to MATLAB for beginners
PPTX
Introduction to matlab lecture 1 of 4
PPTX
Introduction to MATLAB
PPSX
Introduction to MATLAB
PPT
Introduction to MATLAB
PPT
Introduction to Matlab.ppt
PPTX
Matlab introduction
PDF
Basics of matlab
PPTX
Unit -I Toc.pptx
PPTX
Matlab simulink introduction
PDF
MATLAB Basics-Part1
PDF
Matlab-Data types and operators
PPSX
Introduction to MATLAB
Matlab ppt
Introduction to matlab
Basic matlab and matrix
Matlab intro
Matlab Introduction
MATLAB INTRODUCTION
Matlab basic and image
An Introduction to MATLAB for beginners
Introduction to matlab lecture 1 of 4
Introduction to MATLAB
Introduction to MATLAB
Introduction to MATLAB
Introduction to Matlab.ppt
Matlab introduction
Basics of matlab
Unit -I Toc.pptx
Matlab simulink introduction
MATLAB Basics-Part1
Matlab-Data types and operators
Introduction to MATLAB
Ad

Viewers also liked (6)

PDF
Matlab practice
PPTX
Introduction to matlab
PPT
Introduction to matlab
PPTX
Introduction to matlab lecture 2 of 4
PDF
Introduction to matlab_application_to_electrical_engineering
PPTX
Simulink - Introduction with Practical Example
Matlab practice
Introduction to matlab
Introduction to matlab
Introduction to matlab lecture 2 of 4
Introduction to matlab_application_to_electrical_engineering
Simulink - Introduction with Practical Example
Ad

Similar to Introduction to matlab (20)

PDF
PPT
Matlab introduction
PPT
Matlab anilkumar
PPTX
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
PPTX
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptx
PPSX
matlab-130408153714-phpapp02_lab123.ppsx
PDF
PDF
Matlab lec1
PDF
MATLAB Programming
PPT
Matlab Introduction for beginners_i .ppt
PPT
Matlab_Introduction_by_Michael_Medvinsky.ppt
PPT
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PPT
Matlab introduction
PPTX
Lines and planes in space
PPT
Matlab basics
PDF
Matlab guide
PDF
PDF
An Introduction to MATLAB with Worked Examples
PPT
Matlab Tutorial.ppt
Matlab introduction
Matlab anilkumar
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptx
matlab-130408153714-phpapp02_lab123.ppsx
Matlab lec1
MATLAB Programming
Matlab Introduction for beginners_i .ppt
Matlab_Introduction_by_Michael_Medvinsky.ppt
MatlabIntroduction presentation xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Matlab introduction
Lines and planes in space
Matlab basics
Matlab guide
An Introduction to MATLAB with Worked Examples
Matlab Tutorial.ppt

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Cell Structure & Organelles in detailed.
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
human mycosis Human fungal infections are called human mycosis..pptx
TR - Agricultural Crops Production NC III.pdf
Pre independence Education in Inndia.pdf
Sports Quiz easy sports quiz sports quiz
Cell Structure & Organelles in detailed.
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
RMMM.pdf make it easy to upload and study
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial diseases, their pathogenesis and prophylaxis
Supply Chain Operations Speaking Notes -ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
Renaissance Architecture: A Journey from Faith to Humanism
VCE English Exam - Section C Student Revision Booklet
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
FourierSeries-QuestionsWithAnswers(Part-A).pdf

Introduction to matlab

  • 1. An Introduction to MATLAB Santosh K Venu 1
  • 2. What is MATLAB? • MATLAB – MATrix LABoratory: MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory. – MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and animation. 2
  • 3. Stands for MATrix LABoratory • Interpreted language • Scientific programming environment • Very good tool for the manipulation of matrices • Great visualisation capabilities • Loads of built-in functions • Easy to learn and simple to use 3
  • 4. MATLAB Overview • Strengths of MATLAB • Weaknesses of MATLAB 4
  • 5. Strengths 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 5
  • 6. Weaknesses 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, C++) • MATLAB is designed for scientific computation and is not suitable for some things (such as design an interface) 6
  • 7. Matlab Desktop • Command Window – type commands • Workspace – view program variables – clear to clear • clear all: removes all variables, globals, functions and MEX links • clc: clear command window – double click on a variable to see it in the Array Editor • Command History – view past commands • Launch Pad – access help, tools, demos and documentation 7
  • 8. Matlab Desktop - con’t Launch Pad Workspace Current DIrectory Command Window History 8
  • 9. How to Resume Default Desktop 9
  • 10. Matlab Help • Different ways to find information – help – help general, help mean, sqrt... – helpdesk - an html document with links to further information 10
  • 11. Matlab Help - con’t 11
  • 12. Matlab Help - con’t 12
  • 13. Command window • The MATLAB environment is command oriented somewhat like UNIX. A prompt (>>) appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears. • If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt. » a=5; » b=a/2 b= 2.5000 » 13
  • 14. MATLAB Special Variables ans Default variable name for results pi Value of  inf Infinity NaN Not a number e.g. 0/0 i and j i = j = square root of minus one: (-1) (imaginary number) e.g. sqrt(-1) ans= 0 + 1.0000i realmin The smallest usable positive real number realmax The largest usable positive real number 14
  • 15. Variables • No need for types. i.e., int a; double b; float c; • All variables are created with double precision unless specified and they are matrices. Example: >>x=5; >>x1=2; • After these statements, the variables are 1x1 matrices with double precision
  • 16. Working with Matrices and Arrays • Since Matlab makes extensive use of matrices, the best way for you to get started with MATLAB is to learn how to handle matrices. – Separate the elements of a row with blanks or commas. – Use a semicolon ; to indicate the end of each row. – Surround the entire list of elements with square brackets, [ ]. A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
  • 17. MATLAB displays the matrix you just entered: A= 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 • Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can simply refer to it as A. • Keep in mind, variable names are case-sensitive
  • 18. Manipulating Matrices A= 16 3 2 13 5 10 11 8 • Access elements of a matrix 9 6 7 12 >>A(1,2) 4 15 14 1 ans= 3 indices of matrix element(s) • Remember Matrix(row,column) • Naming convention Matrix variables start with a capital letter while vectors or scalar variables start with a simple letter 18
  • 19. MATLAB Relational Operators • MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= 19
  • 20. MATLAB Logical Operators • MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and 20
  • 21. MATLAB Matrices • MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored. • Vectors are special forms of matrices and contain only one row OR one column. • Scalars (1,1)are matrices with only one row AND one column 21
  • 22. MATLAB Matrices • A matrix with only one row AND one column is a scalar. A scalar can be created in MATLAB as follows: » a=23 a= 23 22
  • 23. MATLAB Matrices • A matrix with only one row is called a row vector. A row vector can be created in MATLAB as follows (note the commas): » rowvec = [12 , 14 , 63] or rowvec = [12 14 63] rowvec = 12 14 63 23
  • 24. MATLAB Matrices • A matrix with only one column is called a column vector. A column vector can be created in MATLAB as follows (note the semicolons): » colvec = [13 ; 45 ; -2] colvec = 13 45 -2 24
  • 25. MATLAB Matrices • A matrix can be created in MATLAB as follows (note the commas AND semicolons): » matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9] matrix = 1 2 3 4 5 6 7 8 9 25
  • 26. Extracting a Sub-Matrix • A portion of a matrix can be extracted and stored in a smaller matrix by specifying the names of both matrices, the rows and columns. The syntax is: sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ; where r1 and r2 specify the beginning and ending rows and c1 and c2 specify the beginning and ending columns to be extracted to make the new matrix. 26
  • 27. MATLAB Matrices • A column vector can be • Here we extract column 2 of extracted from a matrix. As the matrix and make a an example we create a column vector: matrix below: » matrix=[1,2,3;4,5,6;7,8,9] » col_two=matrix( : , 2) matrix = col_two = 1 2 3 2 4 5 6 5 7 8 9 8 27
  • 28. MATLAB Matrices • A row vector can be extracted • Here we extract row 2 of the from a matrix. As an example matrix and make a row vector. we create a matrix below: Note that the 2:2 specifies the second row and the 1:3 » matrix=[1,2,3;4,5,6;7,8,9] specifies which columns of the row. matrix = » rowvec=matrix(2 : 2 , 1 : 3) 1 2 3 4 5 6 rowvec = 7 8 9 4 5 6 28
  • 29. Matrices transpose • a vector x = [1 2 5 1] x = 1 2 5 1 • transpose y = x’ y = 1 2 5 1 29
  • 30. Scalar - Matrix Addition » a=3; » b=[1, 2, 3;4, 5, 6] b= 1 2 3 4 5 6 » c= b+a % Add a to each element of b c= 4 5 6 7 8 9 30
  • 31. Scalar - Matrix Subtraction » a=3; » b=[1, 2, 3;4, 5, 6] b= 1 2 3 4 5 6 » c = b - a %Subtract a from each element of b c= -2 -1 0 1 2 3 31
  • 32. Scalar - Matrix Multiplication » a=3; » b=[1, 2, 3; 4, 5, 6] b= 1 2 3 4 5 6 » c = a * b % Multiply each element of b by a c= 3 6 9 12 15 18 32
  • 33. Scalar - Matrix Division » a=3; » b=[1, 2, 3; 4, 5, 6] b= 1 2 3 4 5 6 » c = b / a % Divide each element of b by a c= 0.3333 0.6667 1.0000 1.3333 1.6667 2.0000 33
  • 34. Math & Assignment Operators Power ^ or .^ a^b or a.^b Multiplication * or .* a*b or a.*b Division / or ./ a/b or a./b - (unary) + (unary) Addition + a+b Subtraction - a-b Assignment = a=b (assign b to a) 34
  • 35. Other operators [ ] 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 35
  • 36. The : operator • VERY important operator in Matlab • Means ‘to’ >> 1:10 ans = 1 2 3 4 5 6 7 8 9 10 >> 1:2:10 Try the following ans = >> x=0:pi/12:2*pi; >> y=sin(x) 1 3 5 7 9 Introduction to Matlab 36 Sumitha Balasuriya
  • 37. Length • Max • Mean • Median • Min • Prod • Size • Var • Sum • Det • Rank • Eig • sort/flipr 37
  • 38. Matlab Graphics x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2pi') ylabel('Sine of x') title('Plot of the Sine Function') 38
  • 39. Multiple Graphs t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); plot(t,y1,t,y2) grid on 39
  • 40. • Plotting Multiple Data Sets in One Graph – Multiple x-y pair arguments create multiple graphs with a single call to plot. For example: x = 0:pi/100:2*pi; y = sin(x); y2 = sin(x-.25); y3 = sin(x-.5); plot(x,y,x,y2,x,y3)
  • 41. Multiple Plots t = 0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) subplot(2,2,2) plot(t,y2) 41
  • 42. Graph Functions (summary) • plot linear plot • stem discrete plot • grid add grid lines • xlabel add X-axis label • ylabel add Y-axis label • title add graph title • subplot divide figure window • figure create new figure window • pause wait for user response 42
  • 43. Some Useful MATLAB commands • who List known variables • whos List known variables plus their size • help >> help sqrt Help on using sqrt • lookfor >> lookfor sqrt Search for keyword sqrt in on MATLABPATH. • what >> what ('directory') List MATLAB files in directory • clear Clear all variables from work space • clear x y Clear variables x and y from work space • clc Clear the command window 43
  • 44. Flow Control • if • for • while • break • ….
  • 45. Control Structures Some Dummy Examples • If Statement Syntax if ((a>3) & (b==5)) Some Matlab Commands; if (Condition_1) end Matlab Commands if (a<3) elseif (Condition_2) Some Matlab Commands; elseif (b~=5) Matlab Commands Some Matlab Commands; elseif (Condition_3) end Matlab Commands if (a<3) else Some Matlab Commands; Matlab Commands else Some Matlab Commands; end end
  • 46. Control Structures Some Dummy Examples for i=1:100 • For loop syntax end Some Matlab Commands; for j=1:3:200 for i=Index_Array Some Matlab Commands; Matlab Commands end end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end
  • 47. Control Structures • While Loop Syntax Dummy Example while (condition) while ((a>3) & (b==5)) Matlab Commands Some Matlab Commands; end end
  • 48. Classification of flow %|-------------------------------------| This function classifies a flow | according to the values of the Reynolds (Re) and Mach (Ma). | Re <= 2000, laminar flow 2000 < Re <= 5000, transitional flow Re > 5000, turbulent flow Ma < 1, sub-sonic flow Ma = 1, sonic flow Ma > 1, super-sonic flow %|-------------------------------------| 48
  • 49. Vector Function Consider now a vector function f(x) = [f1(x1,x2,x3) f2(x1,x2,x3) f3(x1,x2,x3)]T, where x = [x1,x2,x3]T (The symbol []T indicates the transpose of a matrix). Specifically, f1(x1,x2,x3) = x1 cos(x2) + x2 cos(x1) + x3 f2(x1,x2,x3) = x1x2 + x2x3 + x3x1 f3(x1,x2,x3) = x1 2 + 2x1x2x3 + x3 2 A function to evaluate the vector function f(x) is shown below. 49
  • 50. Summation %Check if m or n are matrices if length(n)>1 | length(m)>1 then error('sum2 - n,m must be scalar values') abort end %Calculate summation if n and m are scalars S = 0; %initialize sum for i = 1:n %sweep by index i for j = 1:m %sweep by index j S = S + 1/((i+j)^2+1); end end 50
  • 51. Thank U 51