Top Banner

of 28

Matlab Primer Part2

Jun 04, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/13/2019 Matlab Primer Part2

    1/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    Matlab Primer #2 - Programming

    Introduction:Although it has much of the attracti%e high&le%el functionalit" of a software 'pac$age()Matlab is most definitel" a bona-fide computer language with its own programmingconstructs and s"ntax* It is naturall" outside the scope and purpose of this primer centredon Matlab image processing to offer a comprehensi%e treatment of the Matlab language +*,ather) our aim here is to offer a brief discussion -with illustrati%e examples. of the $e"

    programming constructs within -and features of. Matlab* !hus) our brief presentation islimited to essentials in the belief that master" of the details and finer points) as with allcomputer languages) will come through a combination of practice and experience*

    Matrices and Arrays

    Most introductions to the Matlab language begin with a discussion of arra"s and matrices*!his discussion is no exception* !he wa" in which Matlab defines and deals with arra"sand arra" operations is a strong distinguishing feature which allows efficient and compactcode to be written so that grasping the essentials of arra" handling is one of the mostimportant things for the new user to grasp* In fact) it is useful in the beginning to considerthat every quantity (whether numeric or text) created by Matlab is simply an array 2.

    Matlab -an amalgam of MAT rix LAB orator". was originall" designed specificall" toallow eas" and comprehensi%e calculation/manipulation of matrices* Mathematicall"spea$ing) we need to be aware of the distinction between matrices and arrays * Ascomputational ob0ects) matrices are simpl" arra"s i*e* ordered rows and columns of

    numerical %alues* 1owe%er) matrices are a t"pe of arra" to which we attach a definitemathematical meaning and to which certain operations -e*g* matrix multiplication)transpose etc. can be meaningfull" applied* Arra"s on the other hand are often 0ustcon%enient wa"s of storing and organi2ing data which can be numeric) textual or acombination of both and Matlab pro%ides man" useful wa"s of manipulating and dealingwith these 3uite general arra"s* !he $e" point then is that within Matlab there is nodistinction between arrays and matrices * Arra"s and matrices are identical entities and itis onl" the user who can decide if the 3uantit" he has defined is a 'matrix( in the propermathematical sense or simpl" an arra"* In the following discussion) no attempt istherefore made to distinguish between them and it will generall" be clear from contextwhether a gi%en arra" is a matrix*

    + A comprehensi%e treatment is gi%en in Mastering Matlab) 1anselman and 4ittlefield) Prentice 1all* !heextensi%e Matlab documentation pro%ided with the software is also %er" readable and informati%e *5 !his is not strictl" true but sufficientl" close to the truth that it will ser%e its purpose*

    www*fundipboo$*com Matlab Primer 65 +

  • 8/13/2019 Matlab Primer Part2

    2/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    Creating arrays in Matlab

    !he simplest wa" of creating small arra"s in Matlab is to manuall" enter the elements inthe command window) row b" row* !r" entering the commands gi%en below7

    A %ector is 0ust a +&D arra" 7

    8e can turn a row %ector into a column %ector) b" using the transpose operator

    or) of course) transpose a 5&D arra" 7

    8e can also create 9string: arra"s which contain text

    All 2-D arrays must be rectangular or square in other words) to be a legal arra" eachrow in the arra" must ha%e the same number of elements ; * !he same principle applies toarra"s of higher dimension* !hus a legal ;&D arra" must comprise a 'stac$( of 5&D arra"s

    ; So&called cell arra"s and structures are ad%anced data structures which can be used to circum%ent thisrestriction when needed* 8e must defer discussion of these data structures for later examples in the boo$

    but for the impatient reader) t"ping doc struct and doc cell at the Matlab prompt for information onthe basic idea and use*

    www*fundipboo$*com Matlab Primer 65 5

  • 8/13/2019 Matlab Primer Part2

    3/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    of similar dimensions) a legal B&D arra" a group of ;&D arra"s of similar dimensions andso on*

    Accessing indi%idual elements in an array

    Indi%idual arra" elements are accessed using subscripts as follows7&

    8e can change or correct the %alues of arra" elements b" indexing them indi%iduall"7

    Arra"s can be ;&D -or ha%e e%en higher dimensionalit". 7

    Accessing grou"s o& elements in an array ' the colon o"erator

    Matlab has a %er" important and powerful colon operator - : .* !his can be used to create%ectors and for subscripting arra"s* 1ere:s a couple of examples of its use in creating%ectors &

    8e can also access groups of elements in an arra" b" using the colon operator to specif"the %ector indices ( !r" the following 7&

    www*fundipboo$*com Matlab Primer 65 ;

    Matlab Commands What s !a""ening

  • 8/13/2019 Matlab Primer Part2

    4/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    8e can also use the colon operator to extract entire rows or columns of an arra"7&

    8hen we use the colon operator along one of the arra" dimensions in this wa") we areeffecti%el" allowing the index to range over the entire length of that dimension* !hus inthe first example) A-7)+. means we fix the column number e3ual to + and extract all theelements in that column -i*e* the row index %aries from + up to its maximum %alue.* Inthe second example) A-5)7. we fix the row number e3ual to 5 and extract all the elementsin that row -i*e* the column index %aries from + up to its maximum %alue.*

    !r" the exercise below*

    Concatenation o& arrays8e can easil" concatenate -0oin together. arra"s to ma$e a larger arra"* In effect) we 0ustconsider the elements of an arra" to be arrays themselves *

    !he arra"s which form the elements of the concatenated arra" must be of conformabledimension i*e* the resulting arra" must be rectangular* For example) tr"ing to form thearra"s 7

    www*fundipboo$*com Matlab Primer 65 B

    Matlab Commands What s !a""ening

  • 8/13/2019 Matlab Primer Part2

    5/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    does not wor$ and Matlab responds with the appropriate error message

    ??? Error using ==> horzcatAll matrices on a row in the bracketed expression must have thesame number of rows.

    !r" the exercises below7&

    Creating and +ealing With Larger ArraysManual entr" as described abo%e is suitable onl" for relati%el" small arra"s* 4arger arra"scan be created in 5 basic wa"s*

    Matlab pro%ides a number of built in functions for creating and manipulating simplearra"s of arbitrar" dimension* !hese are outlined in the table 5*+ below*

    www*fundipboo$*com Matlab Primer 65

    Primer Exercise 5*5,ead in the Matlab images cameraman.tif and rice.tif -use the imreadfunction.*Concatenate them to ma$e a single image and displa" the result -useimagesc or imsho, function.*

    Primer Exercise 5*;

    Generate the same result as in exercise 5*5* but this time using the Matlabfunction repmat * -Lse the Matlab help facilit" to find out how this function isused.*

  • 8/13/2019 Matlab Primer Part2

    6/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    unction +escri"tion .im"le e*am"le2eros Arra" of 2eros A?2eros-B.ones Arra" of ones A?ones-B.e"e Identit" matrix A?e"e-B.

    repmat Ma$e tiled copies of input arra" A?e"e-B. #?repmat-A)+)5.rand ,andom arra" elements + A?rand-B.randn ormall" distributed random arra" A?randn-B.linspace Nector with linear increments A?linspace- )+)+5.logspace Nector with logarithmic increments A?logspace- )+)+5.meshgrid Ma$e 5&D arra" from 5 input %ectors @O) ?meshgrid-+7+ )+7+ .

    Table 2(/: Matlab &unctions &or creating arrays

    #" suitable manipulation) we can create large arra"s with meaningful contents*!r" the following examples 7

    www*fundipboo$*com Matlab Primer 65

    Matlab Commands What s !a""ening

  • 8/13/2019 Matlab Primer Part2

    7/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    !he last example uses the powerful in&built find function and so&called linear indexing*8e:ll discuss this function and the techni3ue of linear indexing shortl") so don:t worr" ifall the last example is not completel" transparent*

    !hose with some pre%ious programming experience will note from the examples abo%e

    that there are no loop constructs -for) do) while etc. used to build and manipulate thearra"s* A feature of Matlab which distinguishes it from man" other languages is calledimplicit vectorisation * amel") if the input to a Matlab expression is a %ector or arra")

    Matlab $nows to e%aluate the expression at e%er" %alue of the input) producing an outputthat is also a %ector or arra"*

    A second wa" in which larger arra"s can be constructed is through use of appropriateloop constructs* !his is done in a wa" similar to most other languages* !he followingexample assigns the %alue + to all the elements in column +) 5 to all the elements incolumn 5 and so on 7

    !he next example creates an arra" that randoml" allocates %alues of or + to the rows ofan arra" b" 'flipping a coin(7

    As a rule) "ou should tr" to a%oid loop constructs in Matlab where this is possible &especiall" for large arra"s* Matlab is an interpreted language and this means that loopsexecute slowl" compared to compiled code* 4oops are sometimes una%oidable and ha%etheir place in the Matlab language and we shall sa" more about loop constructs later inthis section* !he example below achieves the same purpose as the one abo%e but usesMatlab:s implicit %ectori2ation capabilities

    www*fundipboo$*com Matlab Primer 65 K

    Matlab Commands What s !a""eningEnd for loop

    Matlab Commands What s !a""ening

  • 8/13/2019 Matlab Primer Part2

    8/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    +etermining the si0e o& arrays!he function whos onl" prints information to the screen about the si2e and t"pe of%ariables currentl" existing within the wor$space* !o determine the si2e of an arra" andactuall" assign this information to a %ariable in the wor$space) we must use the in&builtsize function* !he basic s"ntax is !m"n#$si%e(A) where the number of rows and columnsin A are assigned to m and n respecti%el" .

    For example 7

    1ere) dims is a 5 element row %ector containing the number of rows and number ofcolumns* !r" the following 7

    !his time) dims is a ; element row %ector because A is an ,G# colour image and ,G#colour images are a composite of three separate 5&D images) one each for the red) green

    and blue components*

    www*fundipboo$*com Matlab Primer 65 H

    Matlab Commands What s !a""eningCreate + x+ arra" of 2erosI?find-rand-+ )+.< * . A-7)I.?+ >Find indices at which + random

    >numbers exceed threshold and assign

    >corresponding columns of A e3ual to +

    Comments)ote ho, the Matlab code is %ery com"act and that the out"ut o& one &unctioncan directly constitute the in"ut to another 1e(g( find(rand.. etc)

  • 8/13/2019 Matlab Primer Part2

    9/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    Array 3tility &unctionsMatlab pro%ides some further in&built functions for arra" manipulation* Some of these aresummarised in the table below 7

    unction +escri"tion

    reshape Change the shape of an arra"fliplr Trders the columns in re%erse order flipud Trders the rows in re%erse order tril Extracts lower triangular part of arra"triu Extracts upper triangular part of arra"rot ,otates arra" counter&cloc$wise b" oIF

    1ere are some fun examples to tr" out 7

    4elational and logical o"eratorsComparison of two 3uantities is fundamental to an" language* Matlab includes all thecommon relational operators) summari2ed in the table below7&

    4elational 5"erator +escri"tionU 4ess thanU? 4ess than or e3ual to

    V? ot e3ual to< Greater than

  • 8/13/2019 Matlab Primer Part2

    10/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    !r" the examples below 7&

    ote that comparison ta$es place on an element by element basis) returning + where therelation is satisfied and where it is not* ote also the difference between the relationale3ualit" -??. and the assignment operator -?.*

    Warning 7 88 and 8 are distinct operators (The relational o"erator 88 tests &or the e uality o& uantities9 the assignment o"erator 8 is used toassign the out"ut o& an o"eration to a %ariable( This is a common source o& error es"ecially &or

    beginners(

    Logical o"erators4ogical operators allow us to combine or negate relational expressions* Appl"ing theseoperators to relational expressions also results in logical - &+. arra"s ha%ing %alue +where the expression is !,LE and where it is FA4SE*

    !he basic logical operators in Matlab are gi%en in the table below* Some examples oftheir use is illustrated below 7&

    Matlab Logical 5"erator +escri"tion4 ogical A D

    W 4ogical T, V 4ogical T!Matlab Logical &unction +escri"tionand 4ogical A Dor 4ogical T, xor 4ogical exclusi%e T, an" 4ogical !,LE if an" element is !,LEall 4ogical !,LE if all elements !,LEisempt" 4ogical !,LE if matrix is empt"ise3ual 4ogical !,LE if matrices are identicalismember

    www*fundipboo$*com Matlab Primer 65 +

    Matlab Commands What s !a""eningtf assigned %alue + because A is less than #

  • 8/13/2019 Matlab Primer Part2

    11/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    !r" some of these basic examples

    ote from the last example how the output from the function find can directl" form theinput to the function isempty * !his is possible in this specific case because the outputfrom find is a single arra"/matrix and the re3uired input to isempty is also a singlearra"/matrix* !he reader should consult the online help facilit" for further details of thelogical functions described abo%e *

    Matlab lo, ControlMatlab pro%ides flow control statements in a wa" %er" similar to most other

    programming languages* Conditional statements where certain operations are carried outonl" if certain conditions are satisfied can be constructed in two basic wa"s & if andswitch statements*

    I& statementsMatlab supports these %ariants of the if construct &

    if J-statement.*** endif J-statement.*** else J-statement.*** endif J-statement.*** elseif J-statement.*** else J-statement.*** end

    A single example of each %ariant is sufficient to illustrate its use 7&

    www*fundipboo$*com Matlab Primer 65 ++

    Matlab Commands What s !a""eningAssign matrices4ogical A D between logical arra"s AU# and CU#7 ans?@

    +Exclusi%e T, between arra"s AU# and CU#7>ans?@+ + +

    arra"* isempt" tests for this* ans?+

  • 8/13/2019 Matlab Primer Part2

    12/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    oteno semicolon is needed to suppress output at the end of lines containing if" else"elseif or end.!he operator ?? -is e3ual to. is used for logical comparison* It is 3uite distinctfrom the single ? sign which assigns a value to a %ariable*Indentation of if bloc$s is not re3uired) but considered good st"le*

    www*fundipboo$*com Matlab Primer 65 +5

    Matlab Commands What s !a""ening

  • 8/13/2019 Matlab Primer Part2

    13/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    .,itch-case constructsA switch&case construct is similar in basic purpose to an if construct* If a se3uence ofcommands must be conditionall" e%aluated based on the e3ualit" of a single commonargument) a switch&case construct is often easier* 1ere is an example 7

    In the example abo%e) Matlab responds with &ueried file is ' format

    !hus the generic form for a switch statement is

    switch the switch expressioncase a case expression

    corresponding statements.case another case expressionotherwise

    corresponding statements.end

    !hus the corresponding group of legal Matlab statements will be executed if the caseexpression matches the switch expression*

    www*fundipboo$*com Matlab Primer 65 +;

    Matlab Commands What s !a""eninginfo?imfinfo-=cameraman*tif=. >assign image information to structure infoswitch info*Format >switch construct depends on ormat fieldcase Y=tif=Z >execute statement if Format ??:tif: disp-=[ueried file is !IF format=.case Y=0pg=)=0peg=Z disp-=[ueried file is \PG format=. >execute statement if Format ??:0pg:end

    Comments !he Matlab function imfinfo attempts to infer the contents of the image

    cameraman.tif * It assigns the results to a structure called info -a structure is

    essentiall" a collection of numeric and string %ariables each of which can beaccessed using the same basic name but a different specific field.*!"pe help struct at the Matlab prompt for further information

    Tne of the fields in this particular structure is the ormat field* !he switch statementeffecti%el" registers/records the string contained in the format field*

    !his is compared for equality with each of the strings contained within the curl" braces Y Z that are part of the case clauses*

    If e3ualit" occurs) the commands following the case clause are executed*

  • 8/13/2019 Matlab Primer Part2

    14/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    Loo" Constructs for and while for loops allow a set of statements to be executed a fixed number of times* !he s"ntaxis 7

    for x = array statements..

    end

    !he for loop basicall" wor$s b" assigning the loop %ariable x to the next column of the%ector array at each iteration* Consider the following simple for loop to sum all theintegers from + to + 7

    !hus) in this for loop the %ariable i ta$es on the next %alue in the arra" -+)5)**+ . on eachsuccessi%e iteration* !he next example shows a slightl" more ad%anced piece of codein%ol%ing some new Matlab functions & we include it now to show that the basicconstruction of the for loop is exactl" the same 7

    !he following example creates a %ector with the first + terms of the Fibonacci series1 1n n n

    x x x +

    = + using a for loop* Another for loop is then used to c"clicall" permute theterms to form the rows of the image 7

    www*fundipboo$*com Matlab Primer 65 +B

    Matlab Commands What s !a""ening

    sum? >Initialise sumfor i ? +7+ >Create + element arra" i?@+ 5 ;J+ * #egin loop

    sum?sum R i >Calculate cumulati%e sumend >End 4oop

    cumsum-+7+ . > #* !his is the eas" wa" to do this in MatlabJ

    Matlab Commands What s !a""eningA?imread-=cameraman*tif=. #?imread-=moon*tif=. >,ead in two images assign to arra"s a"#?imresi2e-#)si2e-A.)=bilinear=. >,esi2e # to match dimensions of Afor i?+7si2e-A)+. >#egin looping through columns of Ar%als?rand-si2e-A)+.)+. indices?find-r%als< * . >,andoml" sample for pixel

    locations >in columns A-i)indices.?#-i)indices. >At selected pixel locations) cop" #

    >%alues into Aend >End loopimshow-A.

    >Displa" modified image

  • 8/13/2019 Matlab Primer Part2

    15/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    ,hile loo"s!he s"ntax of the while loop is %er" simple &

    while expressionstatements

    end

    In the while loop) expression is a logical expression and the statements following arerepeatedl" executed until the expression in the while statement becomes logicall" false*1ere are a couple of simple examples 7&

    !his example successi%el" generates sets of B random numbers in the inter%al &+* !heloop stops when we obtain a set of B numbers all of which are less than *5 *

    www*fundipboo$*com Matlab Primer 65 +

    Matlab Commands What s !a""ening#egin 4oop%ec-iR+.?%ec-i.R%ec-i&+. >#uild Fibonacci terms

    end >End 4oop

    A-+)7.?%ec >First column of A Fibonacci seriesfor i?+7+ >#egin 4oop A-iR+)7.?@%ec-+K&i7+ . %ec-+7+ &i. >C"cle elements for each new col End >End 4oopimagesc-log-A.. >Displa" on log scale

    Matlab Commands What s !a""eningA?ones-B)+. $? >Initialise A and counter $ while an"-A. >False if A44 elements of A ? A?rand-B)+.< *5 >A is B element logical arra"

    >Element ? + if rand < *$?$R+ >Increment counter end >End loop$ >Show final number of trials

  • 8/13/2019 Matlab Primer Part2

    16/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    More on Arrays and Inde*ing

    8e end this primer with an o%er%iew of some of the more ad%anced aspects of indexinginto arra"s* Indexing into an arra" is a means of selecting a subset of elements from thearra"* Indexing is also closel" related to another term we mentioned in passing earl" on7

    vectori%ation* Nectori2ation means using Matlab language constructs to eliminate program loops) usuall" resulting in programs that run faster and are more readable* !r"out the following examples which illustrate a number of powerful indexing techni3ues*

    Inde*ing ;ectors4et=s start with the simple case of a %ector and a single subscript* !he %ector is7&

    Tr the subscript can itself be another %ector 7

    Matlab=s colon notation - : . pro%ides an eas" wa" to extract a range of elements from %7&

    ou can swap the two hal%es of % to ma$e a new %ector 7

    !he special end operator is an eas" short&hand wa" to refer to the last element of % &

    !he end operator can be used in a range

    ou can e%en do arithmetic using end

    www*fundipboo$*com Matlab Primer 65 +

    'Extract the > third element( ans ?

    Extract the first) fifth) and sixth elements> ans ? + 5 ++

    Extract elements ; to K inclusi%e *> ans ? B 5 ++ K

    Extract the last element> ans ? +B

    %- 7end. > Extract elements to last inclusi%e> ans ? 5 ++ K +B

    %-57end&+. > Extract second to penultimate element > ans ? B 5 ++ K

    Extract and swap the hal%es of %> %5 ? 5 ++ K +B + B

  • 8/13/2019 Matlab Primer Part2

    17/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    !he colon operator is %er" powerful and can be used to achie%e a %ariet" of effects 7

    #" using an indexing expression on the left side of the e3ual sign) "ou can replace certainelements of the %ector*7&

    Lsuall" the number of elements on the right must be the same as the number of elementsreferred to b" the indexing expression on the left* ou can alwa"s) howe%er) use a scalaron the right side*

    !his form of indexed assignment is called scalar expansion*

    Inde*ing Arrays ,ith T,o .ubscri"ts

    ow consider indexing into an arra"* 8e=ll use a magic s3uare for our experiments*

    Most often) indexing in arra"s is done using two subscripts & one for the rows and one forthe columns* !he simplest form 0ust pic$s out a single element 7

    More generall") one or both of the row and column subscripts can be %ectors*

    www*fundipboo$*com Matlab Primer 65 +K

    %-end7&+7+. > ,e%erse the order of elements>ans ? +B K ++ 5 B +

    ,eplace selected elements of % >% ? + + + 5 5 ++ K +B

    ans ? + 5 K

  • 8/13/2019 Matlab Primer Part2

    18/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    A single semi&colon - : . in a subscript position is short&hand notation for *+,end ] and isoften used to select entire rows or columns*

    !he diagram below illustrates a tric$ier use of two-subscript indexing * !he expressionA-@5 ; B ) @+ 5 B . does T! extract elements A-5)+.) A-;)5. and A-B)B. as one might) atfirst glance thin$) but rather extracts the elements shown on the right 7

    .electing scattered elements &rom an arraySuppose "ou do want to extract the -5)+.) -;)5.) and -B)B. elements from A ^ As we ha%e

    0ust shown) the expression A-@5 ; B ) @+ 5 B . doesn:t do this*!here is often confusion o%er how to select scattered elements from an arra"* !odo this re3uires the use of linear indexing and that brings us to our next topic*

    Linear Inde*ing8e begin with a 3uestion* 8hat exactl" does this expression A-+B. do ^ 8hen "ou index into the arra" A using onl" one subscript) MATLAB treats A as if itselements were strung out in a long column vector by going down the columnsconsecutively" as in 7

    +

    J**

    www*fundipboo$*com Matlab Primer 65 +H

    Extract third row> ans ? K +5

    Extract last column> ans ? +; H +5 +

  • 8/13/2019 Matlab Primer Part2

    19/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    H +5 +

    !he expression A-+B. simpl" extracts the +Bth element of the implicit column %ector*

    1ere are the elements of the matrix A along with their linear indices in the top left cornerof each s3uare7&

    !he linear index of each element is shown in the upper left* From the diagram "ou cansee that A-+B. is the same as A-5)B. i*e* inear index $ (column number +) x (numberof rows in array) / row number !he single subscript can be a %ector containing more than one linear index) as in7

    4et:s consider again the problem of extracting 0ust the -5)+.) -;)5.) and -B)B. elements ofA* ou can use linear indexing to extract those elements7

    www*fundipboo$*com Matlab Primer 65 +

  • 8/13/2019 Matlab Primer Part2

    20/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    It:s eas" to see the corresponding linear indices for this example) but how do we computelinear indices in general ^ pro%ides a function called sub ind that pro%ides theappropriate linear indices corresponding to the gi%en row and column subscripts

    !he in&built Matlab function ind sub does precisel" the re%erse) pro%iding the row andcolumn indices gi%en the linear index and the si2e of the arra"*

    The find &unction!he find function was introduced earlier but is %er" useful and so deser%es specialmention* It can be used to extract the indices of all those elements of an arra" satisf"ing astated condition* For example) consider first creating a %ector 7&

    It can also be used on 5&D arra"s to return the row-column indices 7

    Tr it can extract the linear indices of the 5&D arra" 7&

    In the following example we ta$e two images A and # -of e3ual si2e. and compare themon a pixel b" pixel basis to see whether image A has the greater intensit"* If so) we cop"the %alue in A to #*

    Logical Inde*ingAnother indexing %ariation) logical indexing) has pro%ed to be both useful andexpressi%e* In logical indexing) "ou use a single) logical arra" for the matrix subscript*Matlab extracts the matrix elements corresponding to the non2ero %alues of the logicalarra"* !he output is alwa"s in the form of a column %ector* For example) A-A < +5.extracts all the elements of A that are greater than +5*

    www*fundipboo$*com Matlab Primer 65 5

    ,ead in imagesI?find-Aget linear indices for A

  • 8/13/2019 Matlab Primer Part2

    21/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    Man" Matlab functions that start with ] is] - isnan! isreal! isempty..) return logical arra"sand are %er" useful for logical indexing* For example) "ou could replace all the a s B inan arra" with another %alue b" using a combination of isnan) logical indexing) and scalarexpansion* !o replace all a elements of the matrix # with 2ero) use7&

    Tr "ou could replace all the spaces in a string matrix str with underscores7&

    4ogical indexing is closel" related to the find function* !he expression A-A < . ise3ui%alent to A-find-A < ..* 8hich form "ou use is mostl" a matter of st"le and "oursense of the readabilit" of "our code) but it also depends on whether or not "ou need theactual index %alues for something else in the computation* For example) suppose "ouwant to temporaril" replace a %alues with 2eros) perform some computation) and then

    put the a %alues bac$ in their original locations* In this example) the computation istwo&dimensional filtering using filter * ou do it li$e this 7&

    !he Matlab indexing %ariants illustrated abo%e gi%e "ou a feel for wa"s we can createcompact and efficient code* ou will certainl" not need them all right awa" but learningto include these techni3ues and related functions in "our Matlab programs helps to writeand create efficient) readable) %ectori2ed code*

    B a is the I*E*E*E* representation for ot&a&number* A a results from mathematicall" undefinedoperations such as / or inf/inf* An" arithmetic operation in%ol%ing a a and a legal mathematical entit"results in a a * !he" ca) howe%er) sometimes be useful to identif" and/or label locations at which data ismissing*

    www*fundipboo$*com Matlab Primer 65 5+

  • 8/13/2019 Matlab Primer Part2

    22/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    urther !el" in Learning Matlab

    In this brief introduction) we ha%e tried to gi%e an indication and some simple examplesof some of Matlab:s $e" programming constructs hopefull" enough to get "ou off theground* !here are now man" good core Matlab boo$s -non image processing specific.

    and a significant amount of web&based material specificall" aimed at helping usersde%elop their $nowledge of the Matlab language and we refer the reader to a selectedsub&set of this material on the boo$ website -with these primers.*

    8e must also ma$e mention of the excellent on&line help resources and comprehensi%edocumentation a%ailable to Matlab users* In the authors= experience it is clearl" written)well organi2ed and both 3uic$ and eas" to use it almost -but we hope not 3uite. ma$esthe these two supporting Matlab primers for this boo$ superfluous* 8e hasten torecommend this material to the reader*

    As a rather $een DI er) I cannot help but compare programming in Matlab with

    underta$ing some tas$ of ph"sical construction such as building a house* It is a simple but accurate analog"* #uilding a basic house can actuall" be done with a bare minimumof essential tools but it tends to be long&winded and hard wor$* I ha%e often had theexperience of beginning or e%en completing a particular tas$ in building or carpentr"onl" then to disco%er that there is actuall" a much easier wa" to do it) gi%en the right tooland approach* If onl" one had $nown beforehand) how much time and effort could ha%e

    been sa%ed `I loo$ upon the basic $nowledge of %ariable t"pes) arra"s and indexing and $e"

    programming constructs such as for and while loops) conditional if clauses etc that weha%e discussed as the essential tools * 1owe%er) man" of Matlab:s in&built functions are%er" much a$in to specialist tools the" ma$e eas" that which is much harder if "ou tr"to do it all "ourself* !hese da"s) when I am in a hardware store) I often 0ust browse thetool section to see what:s a%ailable 0ust in case I should e%er encounter a future 0ob whichcould ma$e good use of some specialist tool I encounter* In this spirit) we finish this %er"

    brief introduction b" pro%iding the reader with a selected but large list -b" categor". ofMatlab functions together with a brief description of their purpose* Please browse at "ourleisure* !he completel" comprehensi%e list is) of course) a%ailable in Matlab:sdocumentation and the help facilit"*

    !his is a boo$ about image processing so) finall") note that the specialist functionsassociated with the 0atlab image processing toolbox are not yet gi%en here* !he use ofman" of these specialist image processing functions is discussed and demonstrated in theremaining chapters of this boo$* A comprehensi%e list of functions a%ailable is a%ailablein the 0atlab image processing toolbox documentation .

    www*fundipboo$*com Matlab Primer 65 55

  • 8/13/2019 Matlab Primer Part2

    23/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

  • 8/13/2019 Matlab Primer Part2

    24/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    MAT4I> MA)IP3LATI5)

    cat Concatenate arra"s

    reshape Change si2e

    diag Diagonal matrices and diagonals of matrix

    bl#diag #loc$ diagonal concatenation

    tril Extract lower triangular part

    triu Extract upper triangular part

    fliplr Flip matrix in left/right direction

    flipud Flip matrix in up/down direction

    flipdim Flip matrix along specified dimension

    rot$% ,otate matrix degrees

    & ,egularl" spaced %ector and index intomatrix

    find Find indices of non2ero elements

    end

    sub ind 4ast index

    ind sub 4inear index from multiple subscripts

    A44A= 3TILIT= 3)CTI5).

    compan Companion matrix

    gallery 1igham test matrices*

    hadamard 1adamard matrix*

    han#el 1an$el matrix*

    hilb 1ilbert matrix*

    in'hilb In%erse 1ilbert matrix*

    magic Magic s3uare*

    pascal Pascal matrix*

    rosser eigen%alue test matrix*

    toeplitz !oeplit2 matrix*

    'ander Nandermonde matrix*

    wil#inson 8il$inson=s eigen%alue test matrix

    www*fundipboo$*com Matlab Primer 65 5B

  • 8/13/2019 Matlab Primer Part2

    25/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    .P

  • 8/13/2019 Matlab Primer Part2

    26/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    @

  • 8/13/2019 Matlab Primer Part2

    27/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on

    MAT4I> A)AL=.I.

    norm Matrix or %ector norm*

    normest Estimate the matrix 5 norm*

    ran# Matrix ran$*

    det Determinant*

    trace Sum of diagonal elements*

    null ull space*

    orth Trthogonali2ation*

    rref ,educed row echelon form*

    subspace Angle between two subspaces*

    LI)

  • 8/13/2019 Matlab Primer Part2

    28/28

    Fundamentals of Digital Image Processing A Practical Approach with Examples in MatlabChris Solomon !ob" #rec$on