BASICS OF MATLAB 1 120209 MIT AURANGABAD

download BASICS OF MATLAB 1 120209 MIT AURANGABAD

of 207

Transcript of BASICS OF MATLAB 1 120209 MIT AURANGABAD

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    1/207

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    2/207

    Getting Started withGetting Started with

    MATLABMATLAB

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    3/207

    What Is MATLAB?What Is MATLAB?

    The nameThe name MATLABMATLAB stands forstands for matrix laboratorymatrix laboratory

    MATLAB is a highMATLAB is a high--performance language forperformance language for

    technical computing.technical computing.

    It integrates computation, visualization, andIt integrates computation, visualization, andprogramming in an easyprogramming in an easy--to use environment whereto use environment whereproblems and solutions are expressed in familiarproblems and solutions are expressed in familiarmathematical notation.mathematical notation.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    4/207

    The Advantages of MATLAB forThe Advantages of MATLAB for

    technical programmingtechnical programming1.1. Ease of useEase of use2.2. Platform IndependencePlatform Independence

    3.3. PrePre--Defined functionsDefined functions4.4. Device independent plottingDevice independent plotting5.5. Graphical user interfaceGraphical user interface

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    5/207

    MATLAB has evolved over a period of years withMATLAB has evolved over a period of years withinput from many users.input from many users.

    In university environments, it is the standardIn university environments, it is the standard

    instructional tool for introductory and advancedinstructional tool for introductory and advancedcourses in mathematics, engineering, and science.courses in mathematics, engineering, and science.

    In industry, MATLAB is tool of choice for highIn industry, MATLAB is tool of choice for high

    productivity research, development and analysisproductivity research, development and analysis

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    6/207

    MATLAB features a family of addMATLAB features a family of add--on applicationon application--specific solutions calledspecific solutions called toolboxestoolboxes..

    Very important to most users of MATLAB,Very important to most users of MATLAB,

    toolboxes allow you totoolboxes allow you to learnlearn andand applyapply specializedspecialized

    technology.technology.

    Toolboxes are comprehensive collections of MATLABToolboxes are comprehensive collections of MATLABfunctions (Mfunctions (M--files) that extend the MATLABfiles) that extend the MATLABenvironment to solve particular classes of problems.environment to solve particular classes of problems.

    Areas in which toolboxes are available includeAreas in which toolboxes are available includesignal processing, control systems, neuralsignal processing, control systems, neuralnetworks, fuzzy logic, wavelets, simulation, andnetworks, fuzzy logic, wavelets, simulation, and

    many others.many others.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    7/207

    Disadvantages of MATLABDisadvantages of MATLAB

    It is an interpreted language and therefore canIt is an interpreted language and therefore canexecute more slowly than compiled languageexecute more slowly than compiled language

    This problem can be avoided by properlyThis problem can be avoided by properlystructuring the MATLAB programstructuring the MATLAB program

    The second disadvantage is cost: a full copy ofThe second disadvantage is cost: a full copy of

    MATLAB is five to ten times more expensive than aMATLAB is five to ten times more expensive than aconventional C or Fortran.conventional C or Fortran.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    8/207

    The MATLAB SystemThe MATLAB System

    The MATLAB system consists of five main parts:The MATLAB system consists of five main parts:

    Development Environment.Development Environment.The MATLAB Mathematical Function Library.The MATLAB Mathematical Function Library.The MATLAB Language.The MATLAB Language.Graphics.Graphics.

    The MATLAB Application Program Interface (API).The MATLAB Application Program Interface (API).

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    9/207

    Development Environment.

    This is the set of tools and facilities that help youuseMATLAB functions and files.

    Many of these tools are graphical user interfaces.It includes the MATLAB desktop and CommandWindow, a command history, an editor anddebugger, and browsers for viewing help, the

    workspace, files,and the search path.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    10/207

    The MATLAB Mathematical Function

    Library.

    This is a vast collection of computational

    algorithms ranging from elementary functionslike sum, sine, cosine, and complex arithmetic, tomore sophisticated functions like matrix inverse,matrix eigenvalues, Bessel functions, and fastFourier transforms.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    11/207

    The MATLAB Language.

    This is a high-level matrix/array language withcontrol flow statements, functions, data structures,input/output, and object-oriented programming

    features.It allows both programming in the small torapidly create quick and dirty throw-awayprograms,

    and programming in the large to create completelarge and complex application programs

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    12/207

    Graphics.

    MATLAB has extensive facilities for displayingvectors and matrices as graphs,as well as annotating and printing these graphs.It includes high-level functions for two-dimensional and three-dimensional datavisualization, image processing, animation, andpresentation graphics.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    13/207

    The MATLAB Application Program

    Interface (API).

    This is a library that allows you to write C andFortran programs that interact with MATLAB.It includes facilities for calling routines fromMATLAB (dynamic linking), calling MATLABas a computational engine, and for reading andwriting MAT-files.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    14/207

    First Steps in MATLAB

    Starting MATLAB

    To run MATLAB on a PC double-click on the MATLABicon.To run MATLAB on a UNIX system, type MATLAB at theprompt.

    You get MATLAB to do things for you by typing incommands. MATLAB prompts you with two greater-thansigns (>>) when it is ready to accept a command fromyou.

    To end a MATLAB session type quit or exit at the MATLABprompt.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    15/207

    Development EnvironmentDevelopment Environment

    MATLAB DesktopMATLAB DesktopDesktop ToolsDesktop ToolsCommandWindowCommandWindow

    Command HistoryCommand HistoryStart Button and Launch PadStart Button and Launch PadHelp BrowserHelp BrowserCurrent Directory BrowserCurrent Directory BrowserWorkspace BrowserWorkspace BrowserArray EditorArray EditorEditor/DebuggerEditor/Debugger

    ProfilerProfiler

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    16/207

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    17/207

    First Steps in MATLAB

    When starting MATLAB you should see amessage:

    To get started, type one of these commands: helpwin,helpdesk, or demo>>

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    18/207

    First Steps in MATLAB

    When starting MATLAB you should see amessage:

    To get started, type one of these commands: helpwin,helpdesk, or demo>>

    The various forms of help available are :

    Helpwin Opens a MATLAB help GUI

    helpdesk Opens a hypertext help browser

    demo Starts the MATLAB demonstration

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    19/207

    First Steps in MATLABYou can learn how to use any MATLAB command by typing help

    followed by the name of the command,for example, help sin.

    You can also use the lookforcommand, which searches the helpentries for all MATLAB commands for a particular word.

    For example, if you want to know which MATLAB functions to usefor spectral analysis,you could type lookfor spectrum.MATLAB responds with the names of the commands that have thesearched word in the first line of the help entry.

    You can search the entire help entry for all MATLAB commandsby typing lookfor -all keyword .

    To break search press ctrl c keys

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    20/207

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    21/207

    First Steps

    The spacing of operators in formulas does not matter.The following formulas both give the same answer:

    1+3 * 2-1 / 2*41 + 3 * 2 - 1 / 2 * 4

    The order of operations is made clearer to readers of your MATLABcode if you type carefully:

    1 + 3*2 - (1/2)*4

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    22/207

    First Steps DATA TYPEShere are many different types of data that you can work with in MATLAB.You can build matrices and arrays of floating-point and integer data,

    characters and strings, logical true and false states, etc. Two of the MATLABdata types, structures and cell arrays, provide a way to store dissimilar types ofdata in the same array. You can also develop your own data types usingMATLAB classes.There are 15 fundamental data types in MATLAB. Each of these data types is inthe form of a matrix or array. This matrix or array is a minimum of 0-by-0 in

    size and can grow to an n-dimensional array of any size.All of the fundamental data types are shown in lowercase, plain nonitalic text inthe diagram below.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    23/207

    First Steps DATA TYPES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    24/207

    First Steps DATA TYPESIntegers MATLAB has four signed and four unsigned integerdata types. Signed types enable you to work with negative integersas well as positive, but cannot represent as wide a range of numbersas the unsigned types because one bit is used to designate a positiveor negative sign for the number. Unsigned types give you a widerrange of numbers, but these numbers can only be zero or positive.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    25/207

    First Steps DATA TYPESSingle-Precision Floating Point MATLAB constructs the single-

    precision (or single) data type according to IEEE Standard 754 forsingle precision. Any value stored as a single requires 32 bits,formatted as shown in the table below:

    Because MATLAB stores numbers of type single using32 bits,they require less memory than numbers of type double, which use64 bits. However, because they are stored with fewer bits, numbersof type single are represented to less precision than numbers of typedouble.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    26/207

    First Steps DATA TYPESDouble-Precision Floating Point MATLAB constructs the double-

    precision (or double) data type according to IEEE Standard 754 fordouble precision. Any value stored as a double requires 64 bits,formatted as shown in the table below:

    Because MATLAB stores numbers of type single using32 bits,they require less memory than numbers of type double, which use64 bits. However, because they are stored with fewer bits, numbersof type single are represented to less precision than numbers of typedouble.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    27/207

    First Steps DATA TYPES

    The logical data type represents a logical true or false state

    using the numbers 1 and 0, respectively. Certain MATLABfunctions and operators return logical true or false to indicatewhether a certain condition was found to be true or not.For example, the statement

    (5 * 10) > 40 returns a logical true value.Logical data does not have to be scalar; MATLAB supportsarrays of logical values as well. For example, the followingstatement returns a vector of logicals indicating false for thefirst two elements and true for the last three:[30 40 50 60 70] > 40ans =

    0 0 1 1 1

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    28/207

    First Steps DATA TYPESThe logical data

    Creating a Logical Array One way of creating an array of logicalsis to just enter a true or false value for each element. The truefunction returns logical one; the false function returns logical zero:

    >> x = [true, true, false, true, false];

    Logical Operations on an Array You can also perform some logicaloperation on an array that yields an array of logicals:

    >> x = magic(4) >= 9

    >> x =1 0 0 10 1 1 01 0 0 1

    0 1 1 0

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    29/207

    First Steps VARIABLES

    A and a are deferent variables.

    The following are valid MATLAB variable assignments:a = 1

    speed = 1500BeamFormerOutput_Type1 = v*Q*vname = John Smith

    These are invalid assignments:2for1 = yesfirst one = 1

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    30/207

    First Steps VARIABLES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    31/207

    First Steps VARIABLES

    To assign a variable without getting an echo fromMATLAB end the assignment with a semi-colon ;.

    Try typing the following:

    >>a = 2>>b = 3;>>c = a+b;>>d = c/2;

    >>d>>who>>whos>>clear

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    32/207

    First Steps VARIABLES

    >>who

    WHO List current variables.WHO lists the variables in the current workspace.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    33/207

    First Steps VARIABLES

    >>whos

    WHOS List current variables, long form.WHOS is a long form ofWHO. It lists all the variablesin the current workspace, together with information abouttheir size, bytes, class, etc.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    34/207

    First Steps VARIABLES

    >>clear

    CLEAR Clear variables and functions from memory.CLEAR removes all variables from the workspace.

    CLEAR VARIABLES does the same thing.CLEAR GLOBALremoves all global variables.CLEAR FUNCTIONS removes all compiled M- and MEX-functions.

    CLEAR ALLremoves all variables, globals, functionsand MEX links.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    35/207

    First Step

    >>close

    CLOSE Close figure.CLOSE(H) closes the window with handle H.CLOSE, by itself, closes the current figure window.CLOSE ALL closes all the open figure windows.CLOSE ALL HIDDEN closes hidden windows as well.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    36/207

    First Steps

    >>clc

    CLC Clear command window and homes the cursor.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    37/207

    First Steps VARIABLES

    >>home

    HOME Send the cursor home.HOME moves the cursor to the upper left corner of the

    window.W

    hen using the MATLAB desktop, it alsoscrolls the visible text in the window up out of view; youcan use the scroll bar to see what was previously on thescreen.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    38/207

    Typing into MATLABCommand Line EditingIf you make a mistake when entering a MATLAB command, you

    do not have to type the whole line again. The arrow keys can beused to save much typing:

    If you finish editing in the middle of a line, you do not have to putthe cursor at the end of the line before pressing the return key; youcan press return when the cursor is anywhere on the command line.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    39/207

    Typing into MATLAB

    Smart Recall

    Repeated use of the key recalls earlier commands.

    If you type the first few characters of a previous

    command and then press the Key MATLAB willrecall the last command that began with thosecharacters. Subsequent use of will recall earliercommands that began with those characters.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    40/207

    Typing into MATLAB

    Long Lines

    If you want to type a MATLAB command that is too long tofit on one line, you can continue on to the next by endingwith a space followed by three full stops. For example, to typean expression with long variable names:

    Final_Answer = BigMatrix(row_indices,column_indices) + ...Another_vector*SomethingElse;

    Or to define a long text string:

    Mission = [DSTOs objective is to give advice that ...is professional, impartial and informed on the ...application of science and technology that is best ...

    suited to Australias defence and security needs.];

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    41/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    42/207

    The fundamental unit of data in any matlab programThe fundamental unit of data in any matlab programis the arrayis the array

    ARRAYARRAYVECTORSVECTORSROW VECTOR Array with only one dimensionROW VECTOR Array with only one dimension

    COLUMN VECTORCOLUMN VECTORMATRICES two or more dimensionsMATRICES two or more dimensions

    ARRAY( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    43/207

    Typing MatricesTo type a matrix into MATLAB you must

    begin with a square bracket [separate elements in a row with commas or spacesuse a semicolon ; to separate rowsend the matrix with another square bracket ].

    ARRAY( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    44/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    45/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    46/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    47/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    48/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    49/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    50/207

    ( )

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    51/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    52/207

    ( )

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    53/207

    ARRAY ( MATRICES)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    54/207

    The colon operator :

    To generate a vector of equally-spaced elements MATLAB providesthe colon operator. Try the following commands:

    1:5

    0:2:100:.1:2*pi

    The syntaxx:y means roughly generate the ordered set of numbers

    from x to y with increment 1 between them.

    The syntaxx:d:y means roughly generate the ordered set ofnumbers from x to y with increment d between them.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    55/207

    Linspace :

    To generate a vector of evenly spaced points between two end points,you can use the function linspace(start,stop,npoints ):>> x = linspace(0,1,10)x =

    Columns 1 through 70 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667Columns 8 through 100.7778 0.8889 1.0000

    generates 10 evenly spaced points from 0 to 1.

    Typing linspace(start,stop ) will generate a vector of 100 points.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    56/207

    First Steps MATRICES

    For example type :

    >> A=[ 1 2 3;4 5 6;7 8 9]MATLAB responds with

    A =1 2 34 5 6

    7 8 9

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    57/207

    CONCATENATING MATRICES

    ConcatenationConcatenationConcatenationConcatenation is the process of joining small matrices to make bigger ones.is the process of joining small matrices to make bigger ones.

    >> a=[1 2;1 2]>> a=[1 2;1 2]a =a =

    1 21 2

    1 21 2

    >> b=[2 3;2 3]>> b=[2 3;2 3]b =b =

    2 32 32 32 3

    >> c=[a b]>> c=[a b]c =c =

    1 2 2 31 2 2 31 2 2 31 2 2 3

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    58/207

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    59/207

    Useful Matrix Generators

    MATLAB provides four easy ways to generate certain simple

    matrices. These are :

    zeros a matrix filled with zerosones a matrix filled with ones

    Rand a matrix with uniformly distributed random elementsRandn a matrix with normally distributed random elementsEye identity matrix

    To tell MATLAB how big these matrices should be you give thefunctions the number of rows and columns. For example:>> a = zeros(2,3)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    60/207

    Useful Matrix Generators

    MATLAB provides four easy ways to generate certain simple

    matrices. These are :

    zeros a matrix filled with zerosones a matrix filled with ones

    Rand

    a matrix with uniformly distributed random elementsRandn a matrix with normally distributed random elementsEye identity matrixTo tell MATLAB how big these matrices should be you give the

    functions the number of rows and columns. For example:>> a = zeros(2,3)a =

    0 0 0

    0 0 0

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    61/207

    Useful Matrix Generators

    >> b= ones(2,2)

    b=1 11 1

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    62/207

    Useful Matrix Generators

    >> b= ones(2,2)

    b=1 11 1

    >> b = ones(2,2)/2b =0.5000 0.50000.5000 0.5000

    f

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    63/207

    Useful Matrix Generators

    >> b= ones(2,2)

    b=1 11 1

    >> b = ones(2,2)/2b =0.5000 0.50000.5000 0.5000

    >> b = 5*ones(2,2)b =

    5 5

    5 5

    f i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    64/207

    Useful Matrix Generators>> u = rand(1,5)u =

    0.9218 0.7382 0.1763 0.4057 0.9355

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    65/207

    f l i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    66/207

    Useful Matrix Generators

    >> eye(3)ans =

    1 0 0

    0 1 00 0 1

    b i i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    67/207

    SubscriptingMatrix Indexing

    Accessing Single ElementsTo reference a particular element in a matrix, specify its row and columnnumber using the following syntax, where A is the matrix variable.Always specify the row first and column second:A(row, column)

    b i ti

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    68/207

    SubscriptingMatrix IndexingAccessing Single ElementsTo reference a particular element in a matrix, specify its row and columnnumber using the following syntax, where A is the matrix variable.Always specify the row first and column second:A(row, column)

    For example, for a 4-by-4 magic square A,A = magic(4)A = 16 2 3 13

    5 11 10 8

    9 7 6 124 14 15 1

    you would access the element at row 4, column 2 withA(4, 2)

    ans = 14

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    69/207

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    70/207

    SubscriptingLinear IndexingWith MATLAB, you can refer to the elements of a matrix with a single

    subscript, A(k). MATLAB stores matrices and arrays not in the shapethat they appear when displayed in the MATLAB CommandWindow, butas a single column of elements. This single column is composed of all ofthe columns from the matrix, each appended to the last.So, matrix A

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

    4 2 83 5 1

    is actually stored in memory as the sequence2, 4, 3, 6, 2, 5, 9, 8, 1The element at row 3, column 2 of matrix A (value = 5) can also beidentified as element 6 in the actual storage sequence. To access thiselement, you have a choice of using the standard A(3,2) syntax, or you

    can use A(6), which is referred to as linear indexing.

    S b i ti

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    71/207

    Subscripting

    Nonconsecutive Elements

    To refer to nonconsecutive elements in a matrix, use the colonoperator with a step value. The m:3:n in this expression means tomake the assignment to every third element in the matrix. Notethat this example uses linear indexing:B = magic(4);B(1:3:16) = -10B = -10 2 3 -10

    5 11 -10 89 -10 6 12

    -10 14 15 -10MATLAB supports a type of array indexing that uses one array asthe index into another array. You can base this type of indexing oneither the values or the positions of elements in the indexing array.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    72/207

    S bsc ipti g

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    73/207

    SubscriptingIndividual elements in a matrix are denoted by a row index and a column index.To pick out the third element of the vector u type:

    >> u = rand(1,5)u =

    0.9218 0.7382 0.1763 0.4057 0.9355

    >> u(3)ans =0.1763

    You can use the vector [1 2 3] as an index to u. To pick the first three

    elements of u type>> u([1 2 3])ans =

    0.9218 0.7382 0.1763

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    74/207

    Subscripting

    Here is an example of value-based indexing where array B

    indexes into elements 1, 3, 6, 7, and 10 of array A. Inthis case, the numeric values of array B designate theintended elements of A:A = 5:5:50

    A = 5 10 15 20 25 30 35 40 45 50B = [1 3 6 7 10];A(B)ans = 5 15 30 35 50

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    75/207

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    76/207

    SubscriptingRemembering what the colon operator does, you can abbreviate this to>> u(1:3)

    ans =0.9218 0.7382 0.1763

    You can also use a variable as a subscript:

    >> i = 1:3;>> u(i)ans =

    0.9218 0.7382 0.1763

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    77/207

    SubscriptingTwo dimensional matrices are indexed the same way, only you haveto provide two indices:

    >> a = [1 2 3;4 5 6;7 8 9]a =

    1 2 34 5 6

    7 8 9>> a(3,2)

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    78/207

    SubscriptingTwo dimensional matrices are indexed the same way, only you haveto provide two indices:

    >> a = [1 2 3;4 5 6;7 8 9]a =

    1 2 34 5 6

    7 8 9>> a(3,2)ans =

    8

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    79/207

    SubscriptingTwo dimensional matrices are indexed the same way, only you haveto provide two indices:

    >> a = [1 2 3;4 5 6;7 8 9]a =

    1 2 34 5 6

    7 8 9>> a(3,2)ans =

    8>> a(2:3,3)

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    80/207

    SubscriptingTwo dimensional matrices are indexed the same way, only you haveto provide two indices:

    >> a = [1 2 3;4 5 6;7 8 9]a =

    1 2 34 5 6

    7 8 9>> a(3,2)ans =

    8>> a(2:3,3)

    ans =69

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    81/207

    Subscripting

    >> a(2,:)

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    82/207

    Subscripting

    >> a(2,:)

    ans =4 5 6

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    83/207

    Subscripting

    >> a(2,:)

    ans =4 5 6>> a(:,3)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    84/207

    Subscripting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    85/207

    Subscripting>> a(2,:)

    ans =

    4 5 6>> a(:,3)ans =3

    69The last two examples use the colon symbol as an index, which matlab interpretsas the entire row or column. If a matrix is addressed using a single index,matlab counts the index down successive columns:

    >> a(4)ans =2

    >> a(8)ans =

    6

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    86/207

    pTo access the last element of a matrix along a given dimension, use end as asubscript (matlab version 5 or later). This allows you to go to the final element

    without knowing in advance how big the matrix is. For example:>> q = 4:10q =

    4 5 6 7 8 9 10>> q(end)

    ans =10

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    87/207

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    88/207

    pTo access the last element of a matrix along a given dimension, use end as asubscript (matlab version 5 or later). This allows you to go to the final element

    without knowing in advance how big the matrix is. For example:>> q = 4:10q =

    4 5 6 7 8 9 10>> q(end)

    ans =10

    >> q(end-4:end)ans =6 7 8 9 10

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    89/207

    pTo access the last element of a matrix along a given dimension, use end as asubscript (matlab version 5 or later). This allows you to go to the final element

    without knowing in advance how big the matrix is. For example:>> q = 4:10q =

    4 5 6 7 8 9 10>> q(end)

    ans =10

    >> q(end-4:end)ans =6 7 8 9 10>> q(end-2:end)

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    90/207

    pTo access the last element of a matrix along a given dimension, use end as asubscript (matlab version 5 or later). This allows you to go to the final element

    without knowing in advance how big the matrix is. For example:>> q = 4:10q =

    4 5 6 7 8 9 10>> q(end)

    ans =10

    >> q(end-4:end)ans =6 7 8 9 10>> q(end-2:end)ans =8 9 10This technique works for two-dimensional matrices as well:

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    91/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    92/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    >> a(end,end)

    ans =13

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    93/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    >> a(2,end-1:end)

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    94/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    >> a(2,end-1:end)

    ans =2 11

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    95/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    >> a(end-2:end,end-1:end)

    End as a subscript

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    96/207

    p>> a=spiral(4)

    a =7 8 9 106 1 2 115 4 3 1216 15 14 13

    >> a(end-2:end,end-1:end)

    ans =2 113 12

    14 13

    Using Logicals in Array Indexing

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    97/207

    g g y gA logical array index designates the elements of

    an array A based on their position in the indexingarray, B, not their value. In this masking type ofoperation, every true element in the indexingarray is treated as a positional index into thearray being accessed.

    Using Logicals in Array Indexing

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    98/207

    In the following example, B is a matrix of logical ones and zeros. Theposition of these elements in B determines which elements of A aredesignated by the expression A(B):A = [1 2 3; 4 5 6; 7 8 9]A = 1 2 3

    4 5 67 8 9

    B = logical([0 1 0; 1 0 1; 0 0 1]);B = 0 1 0

    1 0 10 0 1

    A(B)ans = 4

    26

    9

    Using Logicals in Array Indexing

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    99/207

    g g y gThe find function can be useful with logical arrays as it returnsthe linear indices of nonzero elements in B, and thus helps to

    interpret A(B):

    find(B)ans = 4

    269

    Using Logicals in Array Indexing

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    100/207

    yLogical Indexing Example 1This example creates logical array B that satisfies thecondition A > 0.5, and uses the positions of ones in B toindex into A:>> A = rand(3);>> B = A > 0.5;>> A(B)=0

    A =

    0.4387 0 0.44560.3816 0.1869 00 0.4898 0

    Logical Indexing Example 2The e t e a le highlight the l ati f the i e be i a agi

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    101/207

    The next example highlights the location of the prime numbers in a magicsquare using logical indexing to set the nonprimes to 0:A = magic(4)A = 16 2 3 13

    5 11 10 89 7 6 12

    4 14 15 1

    B = isprime(A)B = 0 1 1 11 1 0 00 1 0 00 0 0 0

    A(~B) = 0; % Logical indexingA = 0 2 3 13

    5 11 0 00 7 0 0

    0 0 0 0

    Deleting Rows or Columns

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    102/207

    To get rid of a row or column set it equal to the empty matrix [ ].

    a=[1 2 3;3 4 5;5 6 7]a =

    1 2 33 4 55 6 7

    >> a(:,2)=[ ]

    Deleting Rows or Columns

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    103/207

    To get rid of a row or column set it equal to the empty matrix [ ].

    a=[1 2 3;3 4 5;5 6 7]a =

    1 2 33 4 5

    5 6 7

    >> a(:,2)=[ ]a =

    1 3

    3 55 7

    Deleting Rows or Columns

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    104/207

    To get rid of a row or column set it equal to the empty matrix [ ].

    a=[1 2 3;3 4 5;5 6 7]a =

    1 2 33 4 5

    5 6 7

    a(2,:)=[ ]

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    105/207

    Sub arraySub array

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    106/207

    It is possible to use select and subset of MATLAB array asIt is possible to use select and subset of MATLAB array astough they were separate arraytough they were separate array

    a = [ 1 2 3 4;1 2 3 4;1 2 3 4;1 2 3 4]a = [ 1 2 3 4;1 2 3 4;1 2 3 4;1 2 3 4]a =a =

    1 2 3 41 2 3 41 2 3 41 2 3 4

    1 2 3 41 2 3 41 2 3 41 2 3 4

    >> b=a(1:3,1:3)>> b=a(1:3,1:3)

    b =b =

    1 2 31 2 31 2 31 2 3

    1 2 31 2 3

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    107/207

    ConcatenationConcatenation>> a = [1 2 3;4 5 6;7 8 9]

    MATLAB responds witha =

    1 2 34 5 6

    7 8 9

    >> b = [a 10*a; -a [1 0 0;0 1 0;0 0 1] ]

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    108/207

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    109/207

    ConcatenationConcatenationThe repmat function can be used to replicate a matrix:

    >> a = [1 2; 3 4]a =

    1 23 4

    >> repmat(a,2,3)ans =

    1 2 1 2 1 23 4 3 4 3 4

    1 2 1 2 1 23 4 3 4 3 4

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    110/207

    Matrix Concatenation FunctionsMatrix Concatenation Functions

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    111/207

    Matrix Concatenation FunctionsMatrix Concatenation Functions

    A = ones(2, 5) * 6; % 2A = ones(2, 5) * 6; % 2--byby--5 matrix of 6's5 matrix of 6'sB = rand(3, 5); % 3B = rand(3, 5); % 3--byby--5 matrix of random values5 matrix of random valuesC = cat(1, A, B); % Concatenate along the first dimensionC = cat(1, A, B); % Concatenate along the first dimension

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    112/207

    Matrix Concatenation FunctionsMatrix Concatenation Functions>> A>> A

    A =A =6 6 6 6 66 6 6 6 66 6 6 6 66 6 6 6 6

    >> B>> BB =B =

    0.8147 0.9134 0.2785 0.9649 0.95720.8147 0.9134 0.2785 0.9649 0.95720.9058 0.6324 0.5469 0.1576 0.48540.9058 0.6324 0.5469 0.1576 0.48540.1270 0.0975 0.9575 0.9706 0.80030.1270 0.0975 0.9575 0.9706 0.8003

    >> C>> C

    C =C =6.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00000.8147 0.9134 0.2785 0.9649 0.95720.8147 0.9134 0.2785 0.9649 0.95720.9058 0.6324 0.5469 0.1576 0.48540.9058 0.6324 0.5469 0.1576 0.4854

    0.1270 0.0 75 0. 575 0. 706 0.80030.1270 0.0 75 0. 575 0. 706 0.8003

    CONCATENATING MATRICES

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    113/207

    Matrix Concatenation FunctionsMatrix Concatenation Functions

    A = ones(2, 5) * 6; % 2A = ones(2, 5) * 6; % 2--byby--5 matrix of 6's5 matrix of 6'sB = rand(3, 5); % 3B = rand(3, 5); % 3--byby--5 matrix of random values5 matrix of random valuesC = vertcat( A, B); % Concatenate verticallyC = vertcat( A, B); % Concatenate vertically

    CONCATENATING MATRICESi i ii i i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    114/207

    Matrix Concatenation FunctionsMatrix Concatenation Functions>> C>> C

    C =C =6.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00000.8147 0.9134 0.2785 0.9649 0.95720.8147 0.9134 0.2785 0.9649 0.95720.9058 0.6324 0.5469 0.1576 0.48540.9058 0.6324 0.5469 0.1576 0.4854

    0.1270 0.0975 0.9575 0.9706 0.80030.1270 0.0975 0.9575 0.9706 0.8003

    Multidimensional ArraysMultidimensional Arrays

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    115/207

    MATLAB allows to create arrays with many dimensions asnecessary for any given problem

    For example following statements create a 2X3X2 array>> A (:,:,1)= [1 0 1; 1 1 0];>> A(:,:,2) = [9 8 7; 6 5 4];A(:,:,1) =

    1 0 11 1 0

    A(:,:,2) =9 8 7

    6 5 4whos AName Size Bytes ClassA 2x3x2 96 double array

    Grand total is 12 elements using 96 bytes

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    116/207

    Dimensions of the Matrix

    These functions return information about the shapeand size of a matrix.

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    117/207

    LENGTH Length of vector.

    LENGTH(X) returns the length of vector X. It is equivalentto MAX(SIZE(X)) for non-empty arrays and 0 for emptyones.Syntaxn = length(X)

    Example:x = ones(1,8);n = length(x)n =

    8x = rand(2,10,3);n = length(x)n =

    10

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    118/207

    LENGTH Length of vector.LENGTH(X) returns the length of vector X. It is equivalentto MAX(SIZE(X)) for non-empty arrays and 0 for emptyones.Syntaxn = length(X)

    Example:x = ones(1,8);n = length(x)n =

    8x = rand(2,10,3);n = length(x)n =

    10

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    119/207

    Ndims Number of array dimensions

    Syntaxn = ndims(A)

    Description

    n = ndims(A) returns the numberof dimensions in the array A. The number of dimensionsin an array is always greater than or equal to 2. Trailingsingleton dimensions are ignored.

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    120/207

    Ndims Number of array dimensions

    >> a=[1 1 1;1 1 1]a =

    1 1 11 1 1

    >> s=ndims(a)s =2

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    121/207

    Ndims Number of array dimensions

    >> a=[1 1 1;1 1 1]a =

    1 1 11 1 1

    >> a(:,:,2)=[1 1 1;2 2 2]a(:,:,1) =1 1 11 1 1

    a(:,:,2) =

    1 1 12 2 2

    >> s=ndims(a)s =

    3

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    122/207

    NumelNumber of elements in array or subscripted array expression

    Syntaxn = numel(A)

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    123/207

    NumelNumber of elements in array or subscripted array expression

    >> a=magic(2)a =

    1 34 2>> numel(a)ans =

    4

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    124/207

    >> a=magic(2)a =

    1 34 2

    >> a(:,:,2)=a'

    a(:,:,1) =1 34 2

    a(:,:,2) =

    1 43 2

    >> numel(a)ans =

    8

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    125/207

    SizeArray dimensions

    SyntaxD = SIZE(X), for M-by-N matrix X, returns the two-

    element row vector

    [M,N] = SIZE(X), for matrix X, returns the number ofrows and columns in X as separate

    output variables.

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    126/207

    SyntaxD = SIZE(X), for M-by-N matrix X, returns the two-

    element row vector

    >> a=[1 2 3;2 3 4]

    a =1 2 32 3 4

    >> size(a)

    ans =2 3

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    127/207

    Syntax[m,n] = SIZE(X), for M-by-N matrix X, returns the two-

    element row vector

    >> a=[1 2 3;2 3 4]

    a =1 2 32 3 4

    >> [r,c]=size(a)

    r =2

    C=3

    Getting Information About a Matrix

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    128/207

    Syntax[m,n] = SIZE(X), for M-by-N matrix X, returns the two-

    element row vector

    >> a=[1 2 3;2 3 4]

    a =1 2 32 3 4

    >> [r,c]=size(a)

    r =2

    C=3

    Adding Smaller Blocks to a Matrixdd l i h h i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    129/207

    To add one or more elements to a matrix where the sizes arenot compatible, you can often just store the new elements

    outside the boundaries of the original matrix. MATLABautomatically pads the matrix with zeros to keep itrectangular.

    Adding Smaller Blocks to a Matrixdd l i h h i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    130/207

    To add one or more elements to a matrix where the sizes arenot compatible, you can often just store the new elements

    outside the boundaries of the original matrix. MATLABautomatically pads the matrix with zeros to keep itrectangular.Construct a 3-by-5 matrix, and attempt to add a new

    element to it using concatenation. The operation failsbecause you are attempting to join a one-column matrixwith one that has five columns:A = [ 10 20 30 40 50; ...

    60 70 80 90 100; ...110 120 130 140 150];A = [A; 160]??? Error using ==> vertcatAll rows in the bracketed

    expression must have the same number of columns.

    Adding Smaller Blocks to a Matrixthi i b t thi ti d it i h th t

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    131/207

    Try this again, but this time do it in such a way thatenables MATLAB to make adjustments to the size of the

    matrix. Store the new element in row 4, a row that does notyet exist in this matrix. MATLAB expands matrix A by anentire new row by padding columns 2 through 5 with zeros:

    A(4,1) = 160A = 10 20 30 40 50

    60 70 80 90 100110 120 130 140 150

    160 0 0 0 0

    Adding Smaller Blocks to a MatrixA [

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    132/207

    A = [ 10 20 30 40 50; ...60 70 80 90 100; ...110 120 130 140 150];

    You can also expand the matrix by adding a matrix insteadof just a single element:

    A(4:6,1:3) = magic(3)+100

    Adding Smaller Blocks to a MatrixA [ 0 20 0 40 50

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    133/207

    A = [ 10 20 30 40 50; ...60 70 80 90 100; ...110 120 130 140 150];

    You can also expand the matrix by adding a matrix insteadof just a single element:

    A(4:6,1:3) = magic(3)+100A = 10 20 30 40 50

    60 70 80 90 100110 120 130 140 150

    108 101 106 0 0103 105 107 0 0104 109 102 0 0

    Adding Smaller Blocks to a MatrixA [ 10 20 0 40 50

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    134/207

    A = [ 10 20 30 40 50; ...60 70 80 90 100; ...110 120 130 140 150];

    You do not have to add new elements sequentially.Whereveryou store the new elements, MATLAB pads with zeros to

    make the resulting matrix rectangular in shape:A(4,8) = 300

    Adding Smaller Blocks to a MatrixA [ 10 20 30 40 50

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    135/207

    A = [ 10 20 30 40 50; ...60 70 80 90 100; ...110 120 130 140 150];

    You do not have to add new elements sequentially.Whereveryou store the new elements, MATLAB pads with zeros to

    make the resulting matrix rectangular in shape:A(4,8) = 300

    A = 10 20 30 40 50 0 0 0

    60 70 80 90 100 0 0 0110 120 130 140 150 0 0 00 0 0 0 0 0 0 300

    Matrix ArithmeticTh li t f t i l dTh li t f t i l d

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    136/207

    The list of operators includesThe list of operators includes

    + Addition- Subtraction.* Element-by-element multiplication

    ./ Element-by-element division

    .\ Element-by-element left division

    .^ Element-by-element power

    .' Unconjugated array transpose

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    137/207

    Matrix Arithmetic

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    138/207

    Matrices can be added and subtracted(they must be the same size).

    >> d=a*10d =

    10 20 3010 20 30

    10 20 30

    >> d=a.*10d =

    10 20 3010 20 3010 20 30

    Matrix ArithmeticMatrices can be added and subtracted

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    139/207

    (they must be the same size).

    >> a=[1 2 3;1 2 3;1 2 3]a =

    1 2 31 2 31 2 3

    >> d=a/10d =

    0.1000 0.2000 0.30000.1000 0.2000 0.30000.1000 0.2000 0.3000

    >> v=10\av =

    0.1000 0.2000 0.30000.1000 0.2000 0.3000

    0.1000 0.2000 0.3000

    Matrix ArithmeticMatrices can be added and subtracted

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    140/207

    (they must be the same size).

    >> a=[1 2 3;1 2 3;1 2 3]a =

    1 2 31 2 31 2 3

    >> d=a/10d =

    0.1000 0.2000 0.30000.1000 0.2000 0.30000.1000 0.2000 0.3000

    >> v=10\av =

    0.1000 0.2000 0.30000.1000 0.2000 0.3000

    0.1000 0.2000 0.3000

    Matrix ArithmeticMatrices can be added and subtracted

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    141/207

    (they must be the same size).

    >> aa =

    1 2 31 2 31 2 3

    >> bb =

    1 2 31 2 31 2 3

    >> c=a+bc =

    2 4 62 4 6

    2 4 6

    Matrix ArithmeticMatrices can be added and subtracted

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    142/207

    Matrices can be added and subtracted(they must be the same size).

    >> aa =

    1 2 31 2 31 2 3

    >> bb =

    1 2 31 2 3

    1 2 3>> c=a-bc =

    0 0 00 0 0

    0 0 0

    Matrix ArithmeticMatrices can be added and subtracted( h b h i )

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    143/207

    (they must be the same size).

    >> aa =

    1 2 31 2 31 2 3

    >> bb =

    1 2 31 2 31 2 3

    >> m=a*bm =

    6 12 186 12 18

    6 12 18

    Matrix Arithmetic.* Element.* Element--byby--element multiplicationelement multiplication

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    144/207

    yy pp>> aa =

    1 2 31 2 31 2 3

    >> b

    b =1 2 31 2 31 2 3

    >> m=a.*bm =

    1 4 91 4 91 4 9

    Matrix Arithmetic./ Element./ Element--byby--element divisionelement division

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    145/207

    yy..\\ ElementElement--byby--element left divisionelement left division

    >> aa =

    1 2 31 2 31 2 3

    >> bb =

    1 2 31 2 31 2 3

    >> d=a/bWarning: Matrix is singular to working precision.d =

    NaN NaN NaNNaN NaN NaNNaN NaN NaN

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    146/207

    Matrix Arithmetic.^ Element.^ Element--byby--element powerelement power

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    147/207

    yy pp

    >> aa =

    1 2 31 2 31 2 3

    >> b=a^2b =

    6 12 186 12 186 12 18

    >> c=a.^2c =

    1 4 91 4 9

    1 4 9

    Matrix Arithmetic.^ Element.^ Element--byby--element powerelement power

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    148/207

    yy pp>> a

    a =1 2 31 2 31 2 3

    >> c=a^3

    c =36 72 10836 72 10836 72 108

    >> c=a.^3c =1 8 271 8 271 8 27

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    149/207

    Matrix Arithmetic.' Unconjugated array transpose.' Unconjugated array transpose

    i b

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    150/207

    To convert rows into columns use the transpose symbol :

    Be careful when taking the transpose of complex matrices.The transpose operator takes the complex conjugate transpose.If z is the matrix:

    z=[0 0-i;0+2i 1+i]

    z = 0 0 - 1.0000i0 + 2.0000i 1.0000 + 1.0000i

    then z is:>> y=z'y =

    0 0 - 2.0000i0 + 1.0000i 1.0000 - 1.0000i

    Matrix Arithmetic.' Unconjugated array transpose.' Unconjugated array transpose

    i b

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    151/207

    To convert rows into columns use the transpose symbol :

    Be careful when taking the transpose of complex matrices.The transpose operator takes the complex conjugate transpose.If z is the matrix:z=[0 0-i;0+2i 1+i]z =

    0 0 - 1.0000i

    0 + 2.0000i 1.0000 + 1.0000ithen z is:>> y=z'y =

    0 0 - 2.0000i0 + 1.0000i 1.0000 - 1.0000i

    To take the transpose without conjugating the complex elements, usethe . operator. In this case z. is:>> y=z.'y =

    0 0 + 2.0000i

    0 - 1.0000i 1.0000 + 1.0000i

    Array Manipulation FunctionsArray Manipulation Functions

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    152/207

    Rot90 e.g. B = rot90(A)rotates matrix A counterclockwise by 90 degrees.

    a=[1 2 3;3 4 5;4 5 6]a =

    1 2 33 4 54 5 6

    >> b=rot90(a)

    b =3 5 62 4 51 3 4

    Cont

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    153/207

    Eg . Rot90(a,2) rotate array 2*90 degrees counterclockwise

    a=[1 2 3;3 4 5;4 5 6]a =

    1 2 3

    3 4 54 5 6

    >> b=rot90(a,2)

    b =6 5 45 4 33 2 1

    fliplr -Flip matrices left-rightSyntaxB = fliplr(A)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    154/207

    f p ( )Description

    B = fliplr(A) returns A with columns flipped in the left-right direction, that is, about a vertical axis.If A is a row vector, then fliplr(A) returns a vector of thesame length with the order of its elements reversed. If A is acolumn vector, then fliplr(A) simply returns A

    >> a=[1 2;3 4]

    a =1 23 4

    >> b = fliplr(a)b =

    2 1

    4 3

    Flipud-Flip matrices up-downSyntax

    f i d( )

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    155/207

    B = flipud(A)

    DescriptionB = flipud(A) returns A with rows flipped in the up-downdirection, that is, about a horizontal axis.If A is a column vector, then flipud(A) returns a vector ofthe same length with the order of its elements reversed. If A

    is a row vector, then flipud(A) simply returns A.a=[1 2;3 4]a =

    1 23 4

    >> b = flipud(a)b =

    3 41 2

    ContFlipdim- Flip array along a specified dimensionB = flipdim(A dim) returns A with dimension dim flipped

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    156/207

    B = flipdim(A,dim) returns A with dimension dim flipped.

    When the value of dim is 1, the array is flipped row-wise down.When dim is 2, the array is flipped columnwise left to right.flipdim(A,1) is the same as flipud(A), and flipdim(A,2) isthe same as fliplr(A).

    Examplesflipdim(A,1)A = 1 4

    2 5

    3 6produces3 62 51 4

    ReshapeReshape --reshape arrayreshape arrayB = reshape(A,m,n)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    157/207

    returns the m-by-n matrix B whose elements are taken column-

    wise from A. An error results if A does not have m*n elements.a=1:10a =

    1 2 3 4 5 6 7 8 9 10>> b=reshape(a,2,5) % reshape to 2 rows and 5 columns fill bycolumnsb =

    1 3 5 7 92 4 6 8 10

    b=reshape(b,[ ],2) % figures out how many rows are neededb =

    1 62 73 84 95 10

    Diag,triu,tril

    a=[1 2 3;2 3 4;4 5 6]a =

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    158/207

    a =1 2 3

    2 3 44 5 6

    >> diag(a) %extract diagonal using diagans =

    1

    36triu(a) %extract upper triangular partans =

    1 2 30 3 4

    0 0 6tril(a) %extract lower triangular partans =

    1 0 02 3 0

    4 5 6

    Diag,triu,tril

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    159/207

    A = [12 62 93 -8 22];

    B = diag(A)

    B =

    12 0 0 0 00 62 0 0 00 0 93 0 0

    0 0 0 -8 00 0 0 0 22

    Diag,triu,tril

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    160/207

    A = [12 62 93 -8 22];

    B = diag(A, -1)

    B = 0 0 0 0 0 0

    12 0 0 0 0 00 62 0 0 0 00 0 93 0 0 00 0 0 -8 0 0

    0 0 0 0 22 0

    Diag,triu,tril

    [ ]

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    161/207

    A = [12 62 93 -8 22];

    B = diag(A,1)B =

    0 12 0 0 0 00 0 62 0 0 00 0 0 93 0 00 0 0 0 -8 0

    0 0 0 0 0 220 0 0 0 0 0

    Shifting and Sorting MatricesShift and Sort Functions

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    162/207

    Use these functions to shift or sort the elements of a

    matrix.

    You can sort matrices, multidimensional arrays, and cellarrays of strings along any dimension and in ascendingor descending order of the elements. The sort functionsalso return an optional array of indices showing the orderin which elements were rearranged during the sortingoperation.

    Shifting and Sorting MatricesCircular Shift

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    163/207

    CIRCSHIFTShift array circularly.

    B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the valuesin the array A by SHIFTSIZE elements.

    >> a=[1;5;2;3]a =

    1523

    >> b=circshift(a,1)b =3152

    Shifting and Sorting MatricesCircular Shift

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    164/207

    CIRCSHIFTShift array circularly.

    B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the valuesin the array A by SHIFTSIZE elements.

    >> a=[1;5;2;3]a =

    1523

    >> b=circshift(a,2)b =2315

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    165/207

    Shifting and Sorting MatricesCircular Shift

    if i

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    166/207

    CIRCSHIFTShift array circularly.

    B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the valuesin the array A by SHIFTSIZE elements.

    Shifting and Sorting MatricesCircular Shift

    hif i l l

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    167/207

    CIRCSHIFTShift array circularly.

    B = CIRCSHIFT(A,SHIFTSIZE) circularly shifts the valuesin the array A by SHIFTSIZE elements.

    Shifting and Sorting Matrices

    SORT Sort in ascending or descending order

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    168/207

    SORT Sort in ascending or descending order..

    Y = SORT(X,DIM,MODE)has two optional parameters.DIM selects a dimension along which to sort.MODE selects the direction of the sort

    'ascend' results in ascending order'descend' results in descending order

    The result is in Y which has the same shape and type as X.

    Shifting and Sorting Matrices

    SORT Sort in ascending order

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    169/207

    SORT Sort in ascending order..

    >> a=[4;3;2;1]a =

    43

    21

    >> sort(a)ans =

    1234

    Shifting and Sorting Matrices

    SORT Sort in descending order

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    170/207

    SORT Sort in descending order..

    >> aa =

    12

    34

    >> sort(a,1,'descend')ans =

    4321

    Basic Graphics

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    171/207

    Basic PlottingBasic Plotting --Create a plot, include multiple dataCreate a plot, include multiple datasets, specify linestyle, colors, and markers, plotsets, specify linestyle, colors, and markers, plotimaginary and complex data, add new plots, workimaginary and complex data, add new plots, workwith figure windows and axes,and save figures.with figure windows and axes,and save figures.

    Editing PlotsEditing Plots --Edit plots interactively and usingEdit plots interactively and usingfunctions, and use the property editor.functions, and use the property editor.

    Mesh and Surface PlotsMesh and Surface Plots -- Visualize functions ofVisualize functions oftwo variables.two variables.

    Basic PlottingBasic Plotting

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    172/207

    Creating a PlotCreating a PlotMultiple Data Sets in One GraphMultiple Data Sets in One GraphSpecifying Line Styles and ColorsSpecifying Line Styles and ColorsPlotting Lines and MarkersPlotting Lines and Markers

    Adding Plots to an Existing GraphAdding Plots to an Existing GraphFigureWindowsFigureWindowsMultiple Plots in One FigureMultiple Plots in One FigureControlling the AxesControlling the Axes

    Axis Labels and TitlesAxis Labels and TitlesSaving a FigureSaving a Figure

    %Creating a Plot%Creating a Plotx = 0:pi/100:2*pix = 0:pi/100:2*piy = sin(x)y = sin(x)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    173/207

    yyplot(x,y)plot(x,y)

    %Creating a Plot%Creating a Plotx = 0:pi/100:2*pix = 0:pi/100:2*piy = sin(x)y = sin(x)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    174/207

    yyplot(x,y)plot(x,y)

    %%Now label the axes and add a title. The charactersNow label the axes and add a title. The characters \\pi create the symbol .pi create the symbol .

    xlabel('x = 0:2xlabel('x = 0:2\\pi')pi')ylabel('Sine of x')ylabel('Sine of x')

    title('Plot of the Sine Function','FontSize',12)title('Plot of the Sine Function','FontSize',12)

    %Creating a Plot%Creating a Plotx = 0:pi/100:2*pix = 0:pi/100:2*piy = sin(x)y = sin(x)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    175/207

    yyplot(x,y)plot(x,y)

    %%Now label the axes and add a title. The charactersNow label the axes and add a title. The characters \\pi create the symbol .pi create the symbol .

    xlabel('x = 0:2xlabel('x = 0:2\\pi')pi')ylabel('Sine of x')ylabel('Sine of x')

    title('Plot of the Sine Function','FontSize',12)title('Plot of the Sine Function','FontSize',12)Multiple Data Sets in One GraphMultiple Data Sets in One Graphy2 = sin(xy2 = sin(x--.25);.25);y3 = sin(xy3 = sin(x--.5);.5);plot(x,y,x,y2,x,y3)plot(x,y,x,y2,x,y3)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    176/207

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    177/207

    Example..Example..

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    178/207

    x1 = 0:pi/100:2*pi;x1 = 0:pi/100:2*pi;x2 = 0:pi/10:2*pi;x2 = 0:pi/10:2*pi;plot(x1,sin(x1),'r:',x2,sin(x2),'r+')plot(x1,sin(x1),'r:',x2,sin(x2),'r+')

    Adding Plots to an Existing Graph

    The hold command enables you to add plots to an existinggraph When you type

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    179/207

    graph.When you type

    hold on

    MATLAB does not replace the existing graph when you issueanother plotting command; it adds the new data to thecurrent graph, rescaling the axes if necessary.

    for eg.-x1 = 0:pi/100:2*pi;x2 = 0:pi/10:2*pi;plot(x1,sin(x1),'r:);hold on;plot(x2,sin(x2),'r+')

    FigureWindows

    Graphing functions automatically open a new figure

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    180/207

    Graphing functions automatically open a new figure

    window if there are no figure windows already on the screen.If a figure window exists, MATLAB uses that window forgraphics output.

    for eg.-

    x1 = 0:pi/100:2*pi;x2 = 0:pi/10:2*pi;plot(x1,sin(x1),'r:);figure;

    plot(x2,sin(x2),'r+')

    Multiple Plots in One FigureThe subplot command enables you to display multiple plotsin the same window or print them on the same piece of paper.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    181/207

    p p f p pTypingsubplot(m,n,p)

    partitions the figure window into an m-by-n matrix ofsmall subplots and selects the pth subplot for the currentplot.

    for eg.-x1 = 0:pi/100:2*pi;x2 = 0:pi/10:2*pi;subplot(2,1,1)

    plot(x1,sin(x1),'r:');subplot(2,1,2)plot(x2,sin(x2),'r+');

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    182/207

    Setting Axis Aspect Ratioaxis also enables you to specify a number of predefined modes.For example,axis square

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    183/207

    makes the x-axes and y-axes the same length.axis equal

    Setting Axis Aspect Ratioaxis also enables you to specify a number of predefined modes. Forexample,axis squaremakes the x axes and y axes the same length

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    184/207

    makes the x-axes and y-axes the same length.

    axis equal

    Setting Axis VisibilityYou can use the axis command to make the axis visible or invisible.axis onmakes the axis visible. This is the default.axis offmakes the axis invisible.

    Setting Axis Aspect Ratioaxis also enables you to specify a number of predefined modes. Forexample,axis squaremakes the x-axes and y-axes the same length

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    185/207

    makes the x-axes and y-axes the same length.

    axis equal

    Setting Axis VisibilityYou can use the axis command to make the axis visible or invisible.axis onmakes the axis visible. This is the default.axis offmakes the axis invisible.

    Setting Grid LinesThe grid command toggles grid lines on and off. The statement

    grid onturns the grid lines on andgrid offturns them back off again.

    For example:For example:--------

    x1 = 0:pi/100:2*pi;x2 = 0:pi/10:2*pi;subplot(2,1,1)

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    186/207

    x2 0:pi/10:2 pi;subplot(2,1,1)

    plot(x1,sin(x1),'r:');axis squaregrid onsubplot(2,1,2)plot(x2,sin(x2),'r+');axis squaregrid on

    Saving a Figure

    To save a figure, select Save from the File menu. To save itusing a graphics format, such as TIFF, for use with otherapplications, select Export from the File menu. You can alsosave from the command lineuse the save as command,including any options to save the figure in a differentformat.

    Three-Dimensional PlotsThe plot3 command is the 3-d equivalent of plot:

    t = 0: 1:2*pi;

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    187/207

    t 0:.1:2 pi;

    plot3(cos(3*t),sin(3*t),t)

    The three dimensional spiral can be better visualised by changingthe orientation of the axes. You can invoke a mouse-based 3-d axismover by typing:

    Rotate3d

    If you click the mouse button down on the plot and drag, you canmove the axes and view the plot from any angle. Release themouse button to redraw the data. Type rotate3d again to turn off

    this behaviour.

    Mesh and Surface PlotsMesh and Surface Plots

    MATLAB defines a surface by the zMATLAB defines a surface by the z coordinates ofcoordinates of

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    188/207

    MATLAB defines a surface by the zMATLAB defines a surface by the z--coordinates ofcoordinates ofpoints above a grid in the xpoints above a grid in the x--y plane, using straighty plane, using straightlines to connect adjacent points.lines to connect adjacent points.

    TheThe mesh and surfmesh and surfplotting functions displayplotting functions displaysurfaces in three dimensions.surfaces in three dimensions.

    meshmesh producesproduces wireframewireframe surfaces that color only thesurfaces that color only thelines connecting the defining points.lines connecting the defining points.

    surf displays both the connecting lines and the facessurf displays both the connecting lines and the facesof the surface in color.of the surface in color.

    For exampleFor example--

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    189/207

    [X,Y] = meshgrid([X,Y] = meshgrid(--8:.5:8);8:.5:8);R = sqrt(X.^2 + Y.^2) + eps;R = sqrt(X.^2 + Y.^2) + eps;Z = sin(R)./R;Z = sin(R)./R;

    mesh(X,Y,Z,'EdgeColor','black')mesh(X,Y,Z,'EdgeColor','black')figure;figure;surf(X,Y,Z) %surf(X,Y,Z) % A surface plot is similar to a mesh plot exceptA surface plot is similar to a mesh plot exceptthat MATLAB colors the rectangular faces of the surface.that MATLAB colors the rectangular faces of the surface.

    Basic Data AnalysisThe following functions can be used to perform data analysis

    functions:

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    190/207

    max

    maximummin minimumfind find indices of nonzero elementsmean average or meanmedian median

    std

    standard deviationsort sort in ascending ordersortrows sort rows in ascending ordersum sum of elementsprod product of elements

    diffdifference between elementstrapz trapezoidal integration

    cumsum cumulative sumcumprod cumulative productcumtrapz cumulative trapezoidal integration

    max maximumExample:>> a=magic(3)a =

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    191/207

    8 1 63 5 74 9 2

    >> m=max(a)m =

    8 9 7

    >> max(m)ans =

    9>> [v,ind] = max(m)v =9ind =2

    OrOr>> max(max(a))>> max(max(a))ans = 9ans = 9

    find find indices of nonzero elements

    The find function is often used with relational and logical operators:Relational operators == equal to

    l

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    192/207

    ~= not equal to< less than> greater than= greater than or equal to

    Logical operators & AND| OR~ NOTxor EXCLUSIVE ORany True if any element is non-zeroall True if all elements are non-zero

    Find

    >> s = spiral(3)s =

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    193/207

    7 8 96 1 25 4 3We find the elements of s less than 6:>> s> find(s

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    194/207

    Find

    >> s(s>400)ans =700

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    195/207

    700600500800900

    Programming withProgramming withMATLABMATLAB

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    196/207

    Flow ControlFlow ControlMATLAB has several flow control constructs:MATLAB has several flow control constructs:

    ifif

    switch and caseswitch and caseforfor

    IfIfThe if statement evaluates a logical expression and executes aThe if statement evaluates a logical expression and executes agroup of statements when the expression isgroup of statements when the expression is truetrue..

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    197/207

    if expressionif expressionstatementsstatements

    endend

    When you are nesting ifs, each if must be paired with a matching end.When you are nesting ifs, each if must be paired with a matching end.When using elseif and/or else within an if statement, the general formWhen using elseif and/or else within an if statement, the general formof the statement isof the statement is

    if expression1if expression1statements1statements1

    elseif expression2elseif expression2statements2statements2

    elseelsestatements3statements3

    In this example, if both of the conditions areIn this example, if both of the conditions are

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    198/207

    not satisfied, then the student fails thenot satisfied, then the student fails thecourse.course.

    attendance=input('attendance = ');attendance=input('attendance = ');grade_average=input('grade_average =');grade_average=input('grade_average =');if ((attendance >= 0.90) & (grade_average >= 60))if ((attendance >= 0.90) & (grade_average >= 60))disp('pass')disp('pass')

    elseelsedisp('fail')disp('fail')end;end;

    Another exampleAnother example------

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    199/207

    A=input(A=);A=input(A=);B=input(B=);B=input(B=);if A > Bif A > B'greater''greater'

    elseif A < Belseif A < B'less''less'elseif A == Belseif A == B'equal''equal'

    elseelseerror('Unexpected situation')error('Unexpected situation')endend

    switch and caseswitch and caseThe switch statement executes groups of statements based on the value of aThe switch statement executes groups of statements based on the value of avariable or expression.variable or expression.

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    200/207

    For exampleFor example--------method = 'cubic';method = 'cubic';switch (method)switch (method)

    case 'bilinearcase 'bilineardisp('Method is linear')disp('Method is linear')

    case 'cubic'case 'cubic'disp('Method is cubic')disp('Method is cubic')

    case 'nearest'case 'nearest'disp('Method is nearest')disp('Method is nearest')

    otherwiseotherwisedisp('Unknown method.')disp('Unknown method.')endend

    forforRepeat statements a specific number of timesRepeat statements a specific number of times

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    201/207

    SyntaxSyntaxfor variable = expressionfor variable = expressionstatementsstatements

    EndEnd

    forforadd two matrix by using for loopadd two matrix by using for loop

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    202/207

    clc;close all;clear all;a=ones(2,2)b=5*ones(2,2)[row,col]=size(b);

    for i=1:rowfor j=1:col

    c(i,j)=a(i,j)+b(i,j)

    endendc

    forforadd two matrix without using for loopadd two matrix without using for loop

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    203/207

    >> a>> aa =a =

    1 11 11 11 1

    >> b>> b

    b =b =5 55 55 55 5

    >> c=a+b>> c=a+b

    c =c =6 66 66 66 6

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    204/207

    FunctionsFunctions

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    205/207

    Functions are MFunctions are M--files that can accept inputfiles that can accept inputarguments and return output arguments.arguments and return output arguments.The name of the MThe name of the M--file and of the functionfile and of the function

    should be the same.should be the same.For eg.1For eg.1function mean = stat(x)

    n = length(x);mean = sum(x)/n;

    FunctionsFunctions

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    206/207

    Functions are MFunctions are M--files that can accept inputfiles that can accept inputarguments and return output arguments.arguments and return output arguments.The name of the MThe name of the M--file and of the functionfile and of the functionshould be the same.should be the same.

    For eg.2For eg.2function [mean,stdev] = stat(x)n = length(x);

    mean = sum(x)/n;stdev = sqrt(sum((x-mean).^2/n));

    Eg 2.Eg 2.------

  • 8/7/2019 BASICS OF MATLAB 1 120209 MIT AURANGABAD

    207/207

    function [mean,stdev] = stati(x)function [mean,stdev] = stati(x)%STAT Interesting statistics.%STAT Interesting statistics.n = length(x);n = length(x);

    mean = sum(x) / n;mean = sum(x) / n;stdev = sqrt(sum((xstdev = sqrt(sum((x -- mean).^2)/n);mean).^2)/n);