You are on page 1of 18

Fundamentals of Digital Image Processing A Practical Approach with Examples in Matlab Chris Solomon !

ob" #rec$on

Matlab Primer #1 A Fast Start


SECTION I: Matlab and the Image Processing Toolbo
!sing this Primer e""ecti#el$ If "ou are alread" an experienced user of Matlab% most of the material in these two primers will be familiar to "ou& 'ou can either wor$ rapidl" through them or s$ip them entirel" and proceed direct to Chapter ( of the boo$ where we specificall" discuss the fundamentals of how images are defined and handled within the Matlab + Image Processing Toolbox en)ironment& If "ou are new to Matlab% wor$ing through the two primers will *uic$l" get "ou up to speed on the basics& In this primer +part (,% we will aim to achie)e the following-. Explain the ad)antages of using Matlab / the Image Processing !oolbox as a means for practical exploration of image processing& Ad)ise on installation% useful sources of information and describe the basic Matlab interface& Describe and manage the Matlab wor$space& 0ow to write Matlab M files scripts and functions& 0ow to obtain basic graphics output& 0ow to build Matlab expressions&

%h$ &se Matlab ' 1eaders unfamiliar with Matlab are li$el" to as$ wh" we should prefer it to the large number of other scientific computation and )isualisation languages and pac$ages which are now a)ailable& !here are a number of reasons which together ma$e Matlab the right choice for this boo$& 1( )&ic*+to+learn: Matlab is eas" to learn& As "ou will hopefull" see% the learning cur)e for Matlab is shallow& In our experience% "ou can learn and start doing reall" useful things more *uic$l" than with an" other language& ,( Eas$+to+&se: Matlab is eas" to use& It is both an interacti)e en)ironment for high. performance technical computation% graphical displa" and animation +thus offering nearl" all the benefits of specialist 2pac$ages3, and also a high.le)el programming language +pro)iding the necessar" flexibilit" for the user to de)elop his own applications,& -( Integrated en#ironment: Matlab and its associated toolboxes +collections of specialist functions, form a completel" integrated en)ironment& In other words% "ou can de)elop complex software applications which ma" in)ol)e complex calculation% graphical displa" and input and interface to external hardware and ne)er ha)e to mo)e outside the Matlab en)ironment&

www&fundipboo$&com Matlab Primer 4(

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

.( Plat"orm inde/endent: Matlab code and programs run exactly the same on an" computer& !hus "ou need ha)e no concerns about the portabilit" of Matlab code& Matlab is currentl" a)ailable for all main PC operating s"stems& 0( Scienti"ic standard: 5utside the world of computer science per se +part of whose mission should be to ma$e programming easier,% Matlab is emerging as the standard in scientific and technical computation& !he huge growth in the number of Matlab users in 6ni)ersities% research institutions7organisations and companies since its inception in (89: is ample testimon"& 1( 2a/id 3e#elo/ment: !he ease of use and shallow learning cur)e for Matlab itself and functionalit" within Matlab that ma" be new to "ou for an" gi)en tas$ ma$e it an ideal rapid de)elopment +and protot"ping, en)ironment& In man" organi;ations it is used both for initial protot"ping and7or mathematical )erification of implementations that will ultimatel" be de)eloped in an application.le)el de)elopment language such as C7C//7<a)a7Ada& The Matlab Image Processing Toolbo !he Image Processing Toolbox is exactl" what its name suggests a toolbox of speciall" written functions% seamlessl" integrated with Matlab% to perform man" of the low and high le)el procedures which are re*uired time and again whene)er tas$s of image processing are underta$en& !he reason for our choice of Matlab + Image Processing Toolbox ma" be highlighted b" considering two extreme approaches to learning practical% digital image processing& !he low-level approach re*uires the user to write relati)el" detailed code to perform e)en basic tas$s& !his can certainl" lead to understanding if one is tenacious enough to sta" the course but% o)erall progress in learning the concepts is slowed and at least as much is learned about the intricacies of the programming language as the actual image processing& At the other 2high-level extreme% is the push.button or package solution& 5ne sol)es a relati)el" complex problem +e&g& deblurring a nois" image or segmenting an ob=ect from its bac$ground, b" drawing on all the expertise of an expert who has pac$aged the solution into a single clic$ of a button& !he result ma" be *uite good but there is no real dialogue& >o real understanding emerges and it is often not clear how to slightl" modif" or extend the procedure to a sol)e similar but subtl" different problem& As far as the practical implementation of image processing goes% Matlab + Image Processing Toolbox is the time.honoured middle wa"& 'ou can concentrate on the issues avoid unnecessary programming tasks but "ou can?t get awa" with not understanding what "ou are doing& For the more ad)anced reader7user% there is the further moti)ation that all the solutions and corresponding code which "ou ma" de)elop are entirel" portable to the broader Matlab en)ironment% will run on an" machine and% if desired% can be automaticall" con)erted to industr" standard application de)elopment languages such as A>SI C +see Matlab Mex Compiler,&

www&fundipboo$&com Matlab Primer 4(

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

%hat Matlab 4ill be co#ered ' Man" good and comprehensi)e boo$s now exist on the Matlab language& Although fundamentall" simple and eas" to use% Matlab has man" powerful features and extras which we do not and cannot hope to co)er in this !ast-start introduction& 0ere% our aim is to gi)e "ou the essentials that "ou need to get up and running and sufficient material is co)ered here to enable "ou +if "ou are diligent, to tac$le the examples and exercises with confidence& 0owe)er% the moti)ated reader is certainl" strongl" encouraged to broaden their $nowledge b" referring to other boo$s specificall" on the Matlab language as well as the comprehensi)e documentation set which is pro)ided when "ou purchase Matlab +either in paper or electronic form,& SECTION II: Matlab 5asics "ummary o! "ection #ontents Practicalities& 6nderstanding the wor$space& !he @A most essential commands in Matlab& Arra"s and indexing& 1eading% writing and sa)ing data& Data t"pes& 5perators& Flow control& M files functions and scripts& Be" concepts in Matlab& Further references& Practicalities Installing the Matlab So"t4are Indi#id&al 6icenses: For an indi)idual purchasing a standalone license% the installation of Matlab is )er" simple& 'ou will recei)e a CD and a personal license password or $e"& Insert the CD.15M into "our computer dri)e to start the install wi;ard% enter "our password7$e" and follow the remaining )er" simple instructions& Alternati)el" "ou ma" prefer to download the software from the Mathwor$s web.site& !he procedure is similar . with the addition that "ou must in)o$e the install wi;ard "ourself once the software is downloaded& 1efer to the Mathwor$s web.site +www&mathwor$s&com, for details& M&lti+&ser 6icenses: 1esearch Institutions% companies% 6ni)ersities and other organi;ations whose emplo"ees and students use Matlab often ha)e multi.user licenses& !his t"pe of license wor$s b" installing Matlab on a networ$ed ser)er% enabling a number of users to simultaneousl" run Matlab& !he s"stem administrator is then the person usuall" responsible for installing the software& Although installation is usuall" trouble. free% Mathwor$s pro)ide an installation guide which forms part of the on.line documentation pro)ided when "ou purchase Matlab and to which "ou ma" refer& If "ou ha)e difficulties in installing Matlab% "ou should email supportCmathwor$s&com outlining the nature of "our problem& 7etting hel/: As a legitimate user of Matlab "ou are entitled to a)ail "ourself of the technical support which is pro)ided b" The Mathworks +the de)elopers and suppliers of Matlab,& 'ou should email supportCmathwor$s&com and can expect a response to an" meaningful technical *uer" +from the )er" simple to the complex, about the use and scope of Matlab& Dithin reasonable limits% "ou ma" also recei)e good ad)ice on how best to achie)e a technical goal or aim using Matlab& Don?t be afraid to use this ser)ice when "ou need it it is their =ob to pro)ide this ser)ice and the" are enthusiasts&

www&fundipboo$&com Matlab Primer 4(

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

!/grades and b&g+"i es: Matlab is constantl" being de)eloped and refined& Current license holders ma" recei)e new releases of the product depending on the license t"pe and arrangement& 6pgrades and bug.fixes to the software are usuall" a)ailable first from the web.site +www&mathwor$s&com,& 1efer to the instructions contained therein& 6a&nching Matlab Fet us assume that "ou ha)e successfull" installed Matlab& Faunching Matlab is simple& 'ou simpl" double clic$ on the program icon and the Matlab command window appears or alternati)el" t"pe matlab at the command prompt in unix7linux based operating s"stems& The Matlab Command 4indo4 + Finding $o&r 4a$ aro&nd Dhen "ou start Matlab% "ou should get a window loo$ing something loo$ing li$e the frame below& !he st"le and la"out of the drop.down menus is largel" standard& Figure (&( indicates in general terms the basic usage and the specific purpose of the utilities pro)ided b" the menus&

Fig&re 1(1 : The basic start+&/ 4or*+s/ace "or Matlab De assume that "ou ha)e started Matlab the command window is on the screen before "ou and Matlab is read" to recei)e input +as abo)e,& #efore we start exploring Matlab% we first want to tie up two simple but important practical issues which often cause confusion and frustration for beginners& !hese concern - i, the working directory +i&e& the director" or folder in which "ou are running Matlab ii, Matlab?s search path&

www&fundipboo$&com Matlab Primer 4(

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

The %or*ing 3irector$ Dhen "ou start Matlab it runs under a default director"7folder which is determined at the time of installation& Issue the command /4d +2present wor$ing director"3, to find out what "our default wor$ing director"7folder is II pwd MShow present wor$ing director"

As "ou wor$ through the following pages% "ou will want to sa)e Matlab programs and data that "ou ha)e created&& It is best to save your !iles and data in your own specially created and named !older$ Change the current wor$ing director" to the one of "our choice to which "ou ha)e write permission& Consider the example below& !"ping /4d at the prompt on our computer - II pwd ans J e-KMA!FA#Lp(Kwor$ Matlab responds b" showing that the default wor$ing director" on m" computer is e%&M'T(')*p+&work& !o change this to m" own chosen director" e%,chris,my-matlabstu!!% we use the command cd +change director",& II cd e-7chris7m"Gmatlabstuff ans J e-7chris7m"Gmatlabstuff Matlab confirms that the present wor$ing director" is e-7chris7m"Gmatlabstuff& Please note that the directories in this example are of a Microso!t .indows operating s"stem form and are more li$el" to be of the form ,home,chris or ,usr,local,matlab on unix,linux operating s"stems& The Matlab Search Path Dhen "ou t"pe a Matlab command at the prompt and press return% Matlab searches within a certain set of folders7directories to see if it can recognise the gi)en command& !he specific folders which are searched in this wa" are determined b" the search path& !he default search path comprises a limited number of directories +or folders, in which Matlab has organi;ed its own built.in M files and the present wor$ing director"&
www&fundipboo$&com Matlab Primer 4(

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

!"ping the Matlab function /ath will show the current Matlab search path on "our computer& !r" t"ping - II path Sooner or later% "ou will want Matlab to recogni;e commands +or more precisel" functions(, that are not contained within the default search path& !he search path can be displa"ed and modified in se)eral wa"s& 'ou can add directories to the existing search path using the command add/ath with suitable arguments supplied& If% for example% "ou want Matlab to recogni;e files that "ou ha)e written and which reside in the director" c%,chris,my-matlabstu!! "ou should t"pe - II addpath+Nc-7chris7m"Gmatlabstuff?, O

'ou can also achie)e this b" t"ping IIeditpath

which brings up the appropriate path browser for "ou to select the paths "ou wish to add& 'ou can add new directories to the search path at an" time during a Matlab session& It can occasionall" get tedious to add the necessar" folders to "our search path e)er" time "ou start a Matlab session !o a)oid this% "ou can add selected folders to the search path for an indefinite period of time b" editing the Matlab startup file The Matlab Start&/ File Dhen Matlab starts up% it executes a script file called startup$m& #" creating and7or editing this file and adding the appropriate paths to Matlab?s search path using addpath as indicated abo)e% "ou can effecti)el" a)oid ha)ing to set the path each time "ou start Matlab& 5n Microsoft Dindows this file resides in the Matlab startup director" +My /ocuments&M'T(')%or /ocuments&M'T(') depending on 5S )ersion, or within the director" from which Matlab is started on unix7linux 5S platforms& 0or the !ollowing practical session we strongly suggest that you create a !older o! your choice to contain your Matlab work and set the search path to include this !older$

2Commands3 are reall" primiti)e functions& De will discuss !unctions and M files shortl" but the distinction need not concern us here& www&fundipboo$&com Matlab Primer 4(

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

7etting started + The Matlab 4or*s/ace !he first and simplest wa" to use Matlab is to enter commands at the Matlab prompt +usuall" one at a time, and allow Matlab to respond accordingl"& Enter the following se*uence of Matlab commands - %hat8s 9a//ening Mdefine the @ x @ matrix A MDefine the @ x @ matrix # MFet C be the addition of the two matrices

II AJS( @O E :T II #JS@ (O A (T II CJA/#

Matlab responds b" assigning the gi)en matrices to the )ariables A and # and )ariable C was set e*ual to their sum& >ote that in each case% Matlab prints the result of the operation on the screen& !he )ariables A%# and C now exist in the Matlab workspace& !"ping the command whos at the Matlab prompt shows what )ariables currentl" exist in the wor$space - II whos >ame A # C Si;e @x@ @x@ @x@ #"tes Class E@ double arra" E@ double arra" E@ double arra"

Urand total is (@ elements using 8L b"tes

De can use the *uantities A%# and C in subse*uent calculations or operations& Enter the following +including the semi.colon, - II DJAR#.C O IIIJimread+Ncameraman&tif?, O MD J matrix product of A and # with C subtracted M1ead in tif image and assign to )ariable I

!his time "ou will notice that Matlab does not print the results to the screen& !he semi. colon after the command suppresses the output& If "ou omit the semi.colon in the two lines abo)e% both D and all the pixel )alues of the image I +all LHHEL of themP, will print to the screen&
www&fundipboo$&com Matlab Primer 4(

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

!he )ariables D and I now also exist in the wor$space& II whos >ame Si;e A # C D I @x@ @x@ @x@ @x@ @HLx@HL

#"tes Class E@ double arra" E@ double arra" E@ double arra" E@ double arra" LHHEL uint9 arra"

Sa#ing: clearing and loading 3ata !he easiest wa" to sa)e the results of a Matlab session is to use the sa#e command - II sa)e m"session(

!he sa#e command will sa)e all the #ariables we created abo)e in a file called mysession+$mat inside the folder7director" in which "ou are currentl" running Matlab& !he &mat extension on the sa)ed file indicates that this is a Matlab data file& 'ou ma" wish to clear certain )ariables from the wor$space II clear A # C DO whos

!his will show that onl" I +the image, now remains in the wor$space A%#%C and D ha)e all )anished& >ote also that we can t"pe multiple commands on a single line pro)ided the" are separated b" a semi.colon& !he semi colon effecti)el" indicates to the Matlab interpreter that a gi)en command has been entered& !"ping clear with no specific )ariables named will clear all )ariables from the wor$space& II clearO whos

De see that all the )ariables ha)e been erased and the wor$space is now empt"& De ha)e sa)ed the results of our short Matlab session up to now in the file m"session(&mat& 0ow then can we restore these results to the wor$space V De achie)e this )ia the Matlab function load& !r" .

www&fundipboo$&com Matlab Primer 4(

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

II load m"session(O whos

!he )ariables A%#%C%D and I now exist again in the wor$space& M "iles scri/ts and "&nctions !"ping directl" into the command window is a useful wa" to get familiar with Matlab and is ideal for tr"ing out relati)el" simple se*uences of commands& 6sing Matlab in this wa" is somewhat similar to ha)ing a )er" ad)anced des$top calculator "ou don?t need to write 2real programs3 but =ust issue simple commands and "ou get the response bac$ immediatel"& 0owe)er% as "ou de)elop longer and more complex procedures% the limitations of this approach become e)ident and "ou will want to sa)e long se*uences of Matlab commands for future use i&e& the next step up is to write programs& Matlab programs are called 2m.files3 and there are two basic $inds scripts and functions& Matlab Scri/t Files !he simplest form of Matlab program is a so.called script file& A script file is a text file containing a se*uence of )alid Matlab commands& !he following example defines the recipe for how to write and execute +i&e& run, a script file& !r" it out& Creating and r&nning a Matlab Scri/t "ile In the Matlab command window% left.clic$ the !ile drop.down menu and select 1ew 2 )lank M-!ile& !he Matlab text editor appears& De t"pe a se*uence of Matlab commands -

clearO AJimread+Wcameraman&tifW,O #Jimread+Wcircuit&tifW,O imshow+A,O pause+E,O imshow+#,O pause+E,O # J imresi;e+#% si;e+A,,O CJimadd+A%#,O imshow+C,O

%hat8s 9a//ening MFirst clear wor$space of all )ariables M1ead in first tif format image M1ead in second tif format image MDispla" (st image% wait E seconds MDispla" @nd image% wait E seconds M resi;e image # to the si;e of A MDispla" 9.bit sum

De sa)e the text file using the drop.down menu on the text editor + !ile 2 save as,& Sa)e this file +into a folder which is on "our current Matlab search path, with the name add-image$m$ !o run this file% t"pe the name of the script file at the Matlab prompt and press return .

www&fundipboo$&com Matlab Primer 4(

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

IIaddGimage

'ou will find that the indi)idual images are first displa"ed for E seconds each followed b" their 9.bit truncated sum image shown below -.

De ma$e two general comments - An"thing written on a line to the right of a M s"mbol is not interpreted as commands b" Matlab& In other words% an"thing to the right is a comment which is inserted simpl" for explanator" purposes and to ma$e the program comprehensible for the program user& 'ou can edit the script "ou =ust created and include the comment lines in "our script% if "ou wish& All )ariables which are declared7created when a script file is executed exist in the Matlab wor$space when execution is complete& +!"pe whos to confirm that the )ariables A%# and C all exist in the wor$space,

Matlab F&nction Files !he second $ind of m.file is the Matlab function& Functions are also se*uences of Matlab commands but differ from scripts in an important wa"& !he $e" difference between scripts and functions is that when a function is executed only the declared output arguments are returned to the workspace$ An" other )ariables created within the function )anish when Matlab returns to the wor$space& !he simplest wa" to thin$ of a function is as a computational routine which re*uires certain input arguments 3i$e$data7)ariables, to produce re4uired output arguments$ In the traditional programming language sense this is a sub-routine$ !hus% we re*uire from the function that it return the output *uantities we re*uire% gi)en the necessar" input& Intermediate *uantities which might need to be generated to achie)e this aim are of no ultimate interest&

www&fundipboo$&com Matlab Primer 4(

(A

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

Creating and r&nning a Matlab "&nction "ile Function m files are created using the text editor in exactl" the same wa" as scripts& !r" creating the model example function below& Select !ile - 1ew 2 )lank M-!ile from the drop.down menu in the Matlab command window& +alternati)el" select !ile - 1ew 2 0unction M-!ile for a pre. defined function declaration la"out for "ou to edit, !he Matlab text editor appears& %e m&st declare the "&nction on the "irst line( !his declaration is what distinguishes a script from a function& !he function declaration re*uires that "ou specif" the output and input arguments b" chosen names& !he re*uired s"ntax is shown below& 5utput arguments Input arguments Must declare function P

function CJsubGimg+A%#,O

First comment line Mfunction CJsubGimg+A%#,O M!his function accepts as legal input two images of similar si;e A and # M!he output is the difference image CJA.# interpreted as 9.bit +A.@HH, data M!he image is also displa"ed in the default figure window

if si;e+A, XJ si;e+#, disp+NImages are not the same si;e?, returnO else CJimsub+A%#,O imshow+C,O end

MDispla" 9.bit difference image

>ote the following After the function declaration on line (% we ha)e a se*uence of comment lines beginning with a M& Strictl"% these are optional but highl" recommended as a means of describing the basic purpose of the function and the re*uired input and output arguments& After the comments% appears a se*uence of Matlab commands& De sa)e the text file using the drop.down menu on the text editor + !ile 2 save as,& 'ou should choose a name for the function file which exactl" matches the declared function name in the first line of the file& For the example abo)e% use subGimg&m$ !o run this file and see what it does% t"pe the following at the Matlab prompt .

www&fundipboo$&com Matlab Primer 4(

((

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

%hat8s 9a//ening II clearO M clear wor$space II AJimread+Wcameraman&tifW,O #Jimread+Wic&tifW,O M1ead in images II DJsubGimg+A%#,O MExecute function II whos MDispla" )ariables

'ou should see displa"ed the truncated 9.bit difference image of A and #& !he Matlab response to 4hos shows that )ariables A%# and D exist in the wor$space& 7etting hel/ on Matlab "&nctions It is possible to get help on an" Matlab function or operator simpl" b" t"ping help function_name& For example% to get help on how to use Matlab?s general purpose function for reading images into the wor$space imread: we t"pe II help imread

!he +in this case, rather length" response% shows the )ariet" of permissible s"ntaxes for using the function and the acceptable image formats& 'ou can ma$e good use of the help facilit" for $o&r o4n "&nctions in exactl" the same wa"& !r" t"ping . II help subGimg

Matlab responds b" printing to the screen the first unbroken block of comment lines starting with the first comment line +M, that appears within the file -. function CJsubims+A%#,O !his function accepts as legal input two images of similar si;e A and # !he output is the difference image CJA.# interpreted as 9.bit +A.@HH, data !he image is also displa"ed in the default figure window As "ou become more familiar with Matlab and start writing "our own speciali;ed functions% it is good to get into the habit of documenting the use of "our functions in this wa"& !his is a )er" useful wa" of reminding "ourself and other users of the basic purpose of functions +both Matlab?s and "our own, and the re*uired input7output s"ntax&

www&fundipboo$&com Matlab Primer 4(

(@

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

Sa#ing and /rinting gra/hics After getting to grips with the basics% one of the earliest things "ou are li$el" to want to do is to sa)e and print graphics output such as graphs and images& 1un "our script file add;image(m again +II addGimage , to create the figure window containing the truncated 9.bit addition of the images of the cameraman and the integrated circuit& !o print a hard cop" of the figure% select the print option from the Command Dindow menu +!ile 2 print,& !his will in)o$e the default printer for "our s"stem& !o sa)e the figure window to dis$ on "our computer% "ou ha)e two options Select the e /ort option +!ile 2 export, on the command window menu& 'ou are prompted for the t"pe of format in which "ou would li$e to sa)e the graphic and the folder7director" in which "ou want it sa)ed& 'ou use the Matlab /rint function with the specified options& /rint allows "ou to sa)e an image or graph in a )er" large number of standard formats& !"pe For example% t"ping -. II print f( .d=peg Wintegcamera&=pgW

sa)es the displa"ed figure +Figure ( specified as .f(, to the current wor$ing director" as a <PEU format image file with name integcamera$5pg$ An alternati)e is the Matlab imwrite +II doc imwrite, to write image )ariables from the wor$space directl" to an output image file +without surrounding image border,& 'ou ma" )iew the man" possible formats for sa)ing Matlab graphics output b" using the online help facilit" +II help print,& So far in this first section% we ha)e shown "ou some of the basic Matlab commands that "ou need to manage the wor$space& !hese commands +plus some other useful ones, are summarised in the table below& For a more detailed explanation% =ust use the help function +II help 2function name3, at the command window&

www&fundipboo$&com Matlab Primer 4(

(E

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

The ,< Most !se"&l 5asic Matlab Commands


Command="&nction P&r/ose
whos sa)e load clear O +semi.colon, help path pwd diar" more on7off print input loo$for Pause drawnow $e"board t"pe *uit Shows the )ariables existing in the wor$space Sa)es current )ariables to dis$ 1etrie)es sa)ed )ariables and loads them into Matlab Clear )ariables from wor$space Suppresses printing to screen 0elp on s"ntax and use of specific Matlab functions Sets and shows the Matlab director" search path Displa"s the present wor$ing director" +pwd, Sa)es "our Matlab session to a text file !urn Matlab scrolling on7off to one page at a time Print the current acti)e figure to a file Prompt user for input& Search for Pauses program execution for specified time Forces matlab to displa" graphics as the" are created 1eturns control from file to the command window Displa" the contents of an M file on the screen Yuit Matlab

SECTION III: 5&ilding 5asic E /ressions in Matlab Expressions in Matlab emplo" a combination of variables operators numbers and !unctions& For example% in the following expression -.
II xJ(-(A% "Jsin+pi&Rx&7@,

x and y are )ariables% (> and (= are operators% pi and 2 are numbers and sin is a function +>&#& pi is a special case of a built in numerical constant in Matlab,& Im/licit ?ectori@ation If "ou t"pe the expression abo)e at the prompt% "ou will immediatel" notice an interesting and important feature of Matlab& !he )ariable x is a (A element )ector x containing the integers from ( to (A inclusi)e& Dhen we write y = sin+ , as in the
@

example abo)e% Matlab e)aluates the expression at each value o! the input vector : producing an output )ector also of (A elements& !his is sometimes called im/licit

www&fundipboo$&com Matlab Primer 4(

(:

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

#ectori@ation( !he nice thing about implicit )ectorisation is that it helps to a)oid ungainl" loops and allows us to write more compact% intuiti)e expressions@& !r" out the following examples -
IIxJA-pi7EA-pi MMa$e EA element )ector x from A.pi

II"Jcos+x,&[@O plot+x%",

MSample cos[@x at gi)en )alues and plot MUenerate cos @ x and graph function

IIAJS( @O E :T% #JSA (O ( AT IIA.# IIA&[@

MCreate @ x @ matrices A and # MSubtract matrix # from A& ansJS( (O : :T MS*uare each element of A& andJS( :O 8 (LT

A summar" description follows of the wa" in which Matlab defines and deals with variables operators numbers and !unctions& ?ariables Matlab does not re4uire type declarations or dimension statements +as are common re*uirements of other high le)el programming languages,& In this sense we can describe Matlab as a loosely typed programming en)ironment7language& Dhen a new )ariable name is encountered% the appropriate storage space re*uired is automaticall" allocated& IIclearO IIAJS( AO A (T MClear wor$space MStorage for the @x@ arra" A is automaticall" created

Further% the re*uired storage for the )ariable can be dynamically altered& !r" the following -. IIA+E%-, J SH LT MA third row is added to A d"namic allocation occurs

Zariable names must begin with a letter and ma" extend to a maximum of E( alphanumeric characters& >&#& Matlab is case sensiti)e # and b refer to different )ariables&
@

If "ou?)e programmed before in Fortran% Pascal or C7C//% "ou?ll immediatel" recognise the difference&

www&fundipboo$&com Matlab Primer 4(

(H

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

O/erators Expressions ma" emplo" an" of the familiar arithmetic and precedence operators summari;ed in the table below - O/erator / . &7 &R &[ N +, 7 R [ 3escri/tion Addition Subtraction Di)ision +scalar, Multiplication +scalar, Power +scalar, Complex con=ugate transpose Specif" e)aluation order Di)ision +matrix, Multiplication +matrix, Power +matrix,

De build expressions using these operators in the usual wa" - IIxJA-(A% "Jexp+.s*rt+x,,
IIAJS( @O E :T% #JSA (O ( AT% CJS@ (O @ (TO II+A.#,.+#/C, MansJS.( (O ( ET

Matri and scalar o/erators In part two of this primer% we will see that Matlab +deri)ed from Matrix 6aborator", is particularl" powerful for dealing with matrices& Warning ! It is particularly important to be aware from the outset of the difference between the scalar operations for division, multiplication and power exponentiation (./ .* .^) which include a dot before the conventional symbol and and their matrix counterparts (/ * ^) which do not !

www&fundipboo$&com Matlab Primer 4(

(L

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

!r" out the following commands and carefull" digest the difference between them -
IIAJS( @O E :T% #JSA (O ( AT% CJS@ (O @ (TO IIA&[@ MEach element of A is s*uared& ansJS( :O 8 (LT IIARA MMatrix multiplication of A and A& ansJSQ (AO (H @@T IIA[@ MMatrix multiplication implied& ansJSQ (A (H @@T IIA&R# MElement b" element multiplication& ansJSA @O E AT IIAR# MMatrix multiplication& AnsJS@ (O : ET IIA&7C MMatrix Di)ision MDi)ision of corresponding elements& ansJSA&H @ (&H :T

N&mbers >umbers can be expressed using con)entional decimal notation or scientific notation& Matlab handles complex numbers naturall" without an" need for special declarations& Some examples of legal numbers in Matlab are O A&AAE .LQ (Q&HLQ98 E&HHe/Q .(&@Ee.L L/Ei .A&(:@9HQ= Ee/H= +standard decimal, +scientific notation, +complex notation,

>ote that Matlab will interpret i or = as the imaginar" *uantit" ( when written beside a number with no operator between them +e&g& Ei means E ( ,& If an operator appears between them +e&g& E&Ri,% this will be interpreted as the corresponding complex *uantit" provided i is not a )ariable with a preassigned )alue& For example O. II;(JE/:i% ;@JH/(@&R= II=J(-H% ;EJE/:=% "JE/:&R= M;( and ;@ are complex M;E complex% " is real )ector

F&nctions Matlab pro)ides a large number of standard% elementar" mathematical functions +for example exp s4rt log sin etc,& For a complete list of the elementar" functions pro)ided t"pe - II help elfun at the Matlab prompt& As we discussed earlier% functions do not ha)e to be elementar" li$e sin or log& Matlab pro)ides man" high le)el functions and "ou will soon learn to write "our own& 5&ilding E /ressions Matlab expressions are built b" combining )ariables% operators% numbers and functions in a logicall" consistent wa"& 0ere are =ust a few simple examples of legitimate Matlab expressions -

www&fundipboo$&com Matlab Primer 4(

(Q

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

IIclearO IIthetaJpi&7:O II;Jexp+i&Rth, IIw;J;/;&[.( IIimag+w;, II(/+ log+sin+theta,, sin+log+theta,, ,&[i

MansJA&QAQ( / A&QAQ(i MansJ(&:(:@ MansJA MansJA&8QEH . A&AE:(I

In the next part of this primer% we will ta$e a more detailed loo$ at the Matlab language and explore the $e" programming constructs&

www&fundipboo$&com Matlab Primer 4(

(9

You might also like