New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Walker Witting


Marketplace > Rice University > Applied Mathematics > CAAM 420 > COMPUTATIONAL SCIENCE I
Walker Witting
Rice University
GPA 3.58


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in Applied Mathematics

This 80 page Class Notes was uploaded by Walker Witting on Monday October 19, 2015. The Class Notes belongs to CAAM 420 at Rice University taught by Staff in Fall. Since its upload, it has received 10 views. For similar materials see /class/225005/caam-420-rice-university in Applied Mathematics at Rice University.

Similar to CAAM 420 at Rice University

Popular in Applied Mathematics




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/19/15
UMFPACK Lecture 19 CAAM 420 Fall 2004 Task at Hand We constructed the system of equations governing the loop currents in a basic circuit We are faced with the dilemma of how to solve Axb for a sparse matrix A and a given right hand side b source term due to battery to obtain the vector of loop currents x Approach We are going to rely on the technology supplied by Steve Davis s software package UMFPACK As a first step we will save the nonzero entries of the circuit matrix into a file say from Matlab or from emacs depending on how you created your circuit matrix Use coordinate format Next we need to write a piece of C which will read in the sparse matrix coordinate format Use UMFPACK to convert the coordinate storage convention also referred to as triplet storage Perform the trial run factorization then the actual factorization of your circuit matrix Finally use the UMFPACK solve routine to perform the back solve required to solve Axb and compare against the answer given by matlab Get UMFPACK Download UMFPACK to tmpyourusername from httpwwwciseufleduresearchsparseumfpackv43 Uncompress and untar the tarball Examine the contents of the created directory ie read the README cd UMFPACK directory and read the README next make lib lfwhen that compile finishes cd Demo and examine the umfpacksimplec file which gives examples of how to use UMFPACK Customize the code in umfpackdidemoc main function to use your circuit matrix ie use the code in main before UMFPACK Calls To Look At get the default control parameters umfpackdidefaults convert triplet coordinates to compressed sparse row umfpackditripettoco perform trial run factorization umfpackdisymboic perform actual numerical factorization umfpackdinumeric perform back solve umfpackdisolve UMF PACK Demo Files to Look At UMFP ACKDemoumfpacksimplec UMFPA CKDemoMakefile Homework P Create a struct spmat which encapsulates a sparse matrix using coordinate storage triplet storage Save the struct definition in spmath Create a very simple interface function called spmatsetentry which allows you to add an extra nonzero entry to your spmat Use realloc to increase the storage space available Create a spmatinput function which reads in the sparse matrix non zeros from file using a format of your choosing and which in turn uses spmatsetentry to set the entries of a spmat Create an interface function which call s the umfpackdisymboic and umfpackdinumeric UMFPACK functions in order to factorize the matrix Create an interface function which takes as argument an spmat pointer for A and a dvec pointer for b It call s the umfpackdisolve function and returns a dvec pointer for x You should include variables in your spmat struct for the extra structs needed by UMFPACK Test with your circuit matrix and compare the results with the same calculation done using xAb in Matlab PTO Homework P cont Usual report format applies see syllabus Due 102704 This activity is a pledged individual activity You DO NOT need to complete the full algebra for the spmat struct lnclude print outs from your code and from Matlab in your report Use latex and no other type setting software Strongly consider using the report template available at the web site Make your code clearly laid out ie adopt the format for main I discussed previously Solving Linear Systems cont Example systems Lecture 18 CAAM 420 Fall 2004 Note It is important that at least one loop has a resistor that lies only on that loop ie at least one resistor lying on a wire not shared by two loops Otherwise the entire circuit will short circuit around the boundary of the entire circuit Forexample 19 8 Class Exercise Create a nontrivial circuit with 15 sub loops Use a range of resistor values between 1 and 10 Solve for loop currents with Matlab Draw a diagram indicating current along each segment of circuit to two significant figures Verify Kerchoff s first law look it up by checking the sum of currents at three of the wire intersections Count the number of nonzeros of your 15x15 matrix and report the amount of fill ie number of nonzeros225 f Include print out of matlab window used for matrix solution 10V Circuit Problem Enlarged 20V Problem Find the current running through each closed loop 30V 29 3Q 29 3Q 29 3Q 29 Loop Current Matrix Shortcut to To obtain the n th row of the Matrix The diagonal entry is equal to the sum of the resistances on the n th loop There is an off diagonal entry for each neighbor of the loop which is equal to 1 a b sumresistances on shared wire if loop currents are in opposite direction sumresistances on shared wire if loop currents are in the same direction 10V 20V 30V 19 29 3Q 29 3Q 29 3Q 29 Q m m 09 m 6 6 MW 6 m m m m m m m 5 29 4 4 1 m m m m m m m 9 1 Q 09 1 1 1 1 00000lt4u000004100n 0000040005040M 00400000007400 0 000000000400300 000000000000400 000000400007044 000005000M0000 040000400600450 000040047000000 000000U14000000 400 00700143Q000 0000 800000007444U 3004M0004000000 00 B7400ltw0000000 04U00000000000 74740 0000040000 77200504000 123456789mnnmm Using Sparse Matrices in Matlab xnmnwnlsandset nw 39nnh n E a 51 3 mommuzsauasmnmrmmskm 5 m gm Lext gag magmas We Mam gag Ede gm law ext 9911th magmas Wag ndw ap 3635 Data quotMfgtE339EzJ A A 3 A 3 ABLE S V H C x O x O 0 51mewa C o C 0 lt3 0 lt3 V 0000000000 0 OOOOOOOOO 000000 0000000000 00 4 384 39 000 l FNMVLOLONOOCD O O O O O T 46 14 10 2 00000 00000 000000 000000 0 V 00000 O m r C b C o C T o Cgt Cgt 0 1 000000000 000 T 7 cgt o cgt cgt o b cgt o T 00000 O 0 0000000 000 V V O 7 OOOOOOOOOOOOH l m OOVDOOO d J 10 1 Rez y 000 m OOOOOOOOO 00005000 7 OOOOOOOO OOOOOOOO 1 N V quot1000 O ltfv 1 O T O 0 00000000 r 1 HHHHNNNNMMMG WWHUmkakOkOhhhhhoooommmrmoo r lt lt LO 0 0 O O O O O 9 m Lo H 00 y oy I 0 0 rowcoumnentry Run bigcircui 1 Create the list of nonzeros 2 Convert the list to Matlab s sparse matrix format 3 Convert the sparse matrix to a full matrix just for viewing min DamianHA File gnu Vim we Windaw 5 cummnimclarv cnamemsmsmngsumwewp gtgt bigcircuit spoonvert CA gtgt full sparseA ans gtgti Rzadv Counting the NonZeros with nnz We can use Matlab s built in nnz function to find the number of nonzeros Aglzl Etta Edit ngw Wat WJndnw ak A i g 7 icunanoivmmy cnncumemsmsmngsmmvasnap a FL DB ans 2 1 gtgt nnz sparseA 289 possible Le there are only 58 nonzero entries out of 17x17 Haadv Sparse Matrices When the fill ratio of a matrix is small ie very w nonzero entries in the matrix we can use fe an alternative to storing all the entries in the matrix Next time we will discuss different ways to ore the nonzero entries omitting the zeros We will then review available libraries designed to allow manipulation of sparse matrices Valuable references and online book httpwwwuserscsumnedusaadbookshtm Storage Conventions There are many different conventions used to store a sparse matrix Refer to ftpftpcsumnedudeptuserssaadPSiter1pdf Chapter 3 Sparse Matrices page 84 for details We will briefly cover 3 common methods to store the nonzero entries of a sparse matrix compressed sparse row compressed sparse column coordinate format Compressed Sparse Row Convention Row compressed Imagine we take a row major dmat indexed from 1 and strip out the zero entries from the storage vector At the same time we also create two arrays used for indexing The first array has nrows1 int entries The n th entry is the location in the stripped storage vector of the first nonzero entry for row n of the matrix The last entry in this array is the number of nonzeros1 The second array of int s is the same size as the stripped storage vector and contains the column number of each entry Example Supposeouroriginalmatrixis o 12 0 16 0 32 11 23 22 Then the nonzero entries in rowmajor ordering are 12 16 32 11 23 22 The array of location in nonzero entries of first entry on a row is 1 2 4 7 where we have padded the last entry to be the total number of nonzero entries 1 Finally the vector of column numbers for each entry are 213123 Class Exercise compressed sparse row format N to O i 1 O O O N O O O 39 What is the nonzero entries matrix What is the first nonzero entry in a row locator What is the column index per nonzero entry array Compressed Sparse Column Convention Same as rowcondensed version but this time the columns are treated instead of the rows Class Exercise compressed sparse column format N to O i 1 O O O N O O O 39 What is the nonzero entries matrix What is the first nonzero entry in a row locator What is the column index per nonzero entry array Coordinate Format Storage An easier format stores each nonzero entry directly stores the coordinates and value of the entry namely row numbercolumn number entry value 0 12 0 cntrics12 16 32 11 23 22 16 0 32 column2 1 3 1 2 3 11 23 22 row1 2 2 3 3 3 Some Software for Sparse Matrices SPARSKIT includes BLAS type functionality for sparse matrices httpwwwuserscsumned usaadsoftwareS PARSKITsparskithtml ftpftpcsumnedudeptsparse UMFPACK includes fast multi frontal solvers for sparse matrices httpwwwcise ufleduresearchsparseu mfpack Class Exercise using a library from the web For the following make a directory tmpusername You will work in this directory to avoid going over your quota in your home directory Download SPARSKIT2 from the ftp link at httpwww userscsumnedusaadsoftwareSPARSKITsparskithtml Use gzip and tar to extract the contents of the downloaded file Examine the contents of the directory which is created Wait for further instructions Introduction to C Part 2 Lecture 21 CAAM 420 Fall 2004 Class Exercise Download mydoublecpp and mydoubleh Using the mydouble class compute 3142314231 174231311717 How many operations does each take C Passing by Reference In C we have two options for passing variables as arguments to a function We either pass in a copy of the variable or we pass in a copy of the pointer to a variable If we pass the copy of the variable the function is not able to change the original If we pass the copy of the pointer to the variable the function can fuse the pointer address to find and change the variable itsel However using pointers in this way can cause problems We do not have access control ie there is no barrier to the user taking control of the pointer by writing over it or accessing the memory directly Furthermore the pointer can be copied but not all copies may be current if say a realloc call is made A more elegant C solution is to pass a variable by reference to a function assing by Reference Demo purpose demonstrate passing by reference inciude ltiostreamgt USing namespace std inputoutput argument a passed by reference void myfunctionCdoubie ampa a 31 since a is a reference we are changing the originai int mainCint argc char H argva doubie a 22 cout ltlt a before caii ltlt a ltlt n notice we pass the variabie in just as usuail myfunctionCa cout ltlt quota after caii ltlt a ltlt n J LII I9 I CIO Jung1e g o myreference myreferencecpp A A A lt F1 myreji e rence cpp J ung39l e Jung1e m reference a before ca 1 22 a after caii 31 jungie I return 0 Passing by Reference mydouble ciass mydoubie private doubie vaiue char name pubiic mydoubieC defauit constructor mydoubieCdoubie a char aname constructor mydoubieCconst mydoubie ampa copy constructor mydoubieC destructor mydoubie operatormydoubie ampb return this objectb mydoubie operatorCmydoub1e ampb return this obJectb mydoubie operator Cmydoubie ampb return this object b mydoubie operatormydoubie ampb return this objectb void printC print this object to screen I changed the operator definitions to pass by reference rather than by copy cont I also had to update the implementations of mydoub39le mydoub39le operatormydoub39e 8b char newnameEBUFSIZ sprtnthnewname s s name bname I mydoub1e Cvatuebva1ue newname return c mydoubte mydoubteoperatormydoub1e ampb char newnameEBUFSIZ sprtnthnewname s s name bname mydoub1e cha1uebva1ue newname return C m doub1e m doub1eoerator m39doub1e ampb 1 lt C AaFev L5 With and wout Passing by Reference jung1e mydoub1e mydoub1emydoub1e bui1ding a mydoub1emydoub1e bui1ding b mydoubWemydoub1e cop ing b mydoub1emydoub1e bui ding a COB b3 mydoub1em doub1e de1ete1ng copyC g P b a copbeD 1 200000 aSng ycopy mydoub1emydoub1e de1eteing a copbeD mydoub1emydoub1e de1eteing b mydoub1emydoub1e de1eteing a jung1e I Jung1e mydoub1eref mydoub1emydoub1e bui1ding a mygoug1emygouge Buj3jng E b my ou emy ou e u1 1ng a VVwaaSngbyre Hence a b l200000 mydoub1emydoub1e de1eteing a b mydoub1emydoub1e de1eteing b mydoub1emydoub1e de1eteing a jung1e I Using stringh To make the transition easier I used the C approach to strings in mydouble namely using an array of char s as a string This was passed between functions as a pointer buried in the class The next stage of the C evolution is to use the C string object which is part of the standard library p48 amp p582 Stroustrup The C string objects can be constructed destructed added together concatenated compared I also used the iostream output approach we saw last time Using string instead of char inciude ltiostreamgt us1ng namespace std inciude quotmydoubiestringh defauit constructor mydoubiemydoub1e cout ltlt quotmydoubiemydoubie defauit constructorn Using the oout stream Using the string Class Using the gt string copy constructor vaiue name 0 quotdefauitquot constructor mydoubiemydoubieCdoubie a string aname cout ltlt mydoubiemydoubie buiiding ltlt aname ltlt n name aname vaiue a Adding string s Together Now we can construct the string names in an obvious way cog constructor mydou emydoub1econst mydoub1e ampa name COPYC aname D cout ltlt quotmydoub1emydoub1e copying ltlt aname ltlt quotn va1ue ava1ue copy vatue from a destructor mydoub1emydoub1e cout ltlt mydoubtemydoub1e de1etetng 39 ltlt name ltlt quotn mydoub1e mydoub1eoperatormydoub1e ampb Pdo ce hOVVVVe string newname quotCquot name quot bname quotDquot JUSt add together mydoub39le Cva39l uetbAa39l ue newname the components of the string return C Finally the demo code At the highest level we see no difference in the constructor calls The compiler provides the conversion of a to a C string void mydoubleprint cout ltlt name ltlt ltlt value ltlt n int mainCint argc char argv mydouble aC 20 aquot mydouble b 32 b mydouble c ab cprint Function Overloading p149 Stroustrup If two functions perform the same task on objects of different types it is possible to use the same function name for both At compile time the compiler will decide which function to call based on the arguments used There may be ambiguity You cannot overload create two functions which have the same name same argument types but different return variable type The return type is not taken into account for function overloading Function Overloading Example Here we overload a function called myadd purpose demonstrate function overloading inciude ltiostreamgt US1ng namespace std int myaddCint a int b cout ltlt quotin integer myaddn return ab doubie myaddCdouble a doubie b cout ltlt in double myaddn return ab jungie g o myoverload myoverloadcpp jungie Jungle myoverload 1n doubie myadd in integer myadd double da 12 db 32 39 gbie 213 414 int 1a 2 1b l jung1e I nt mainCint argc char argv double daplusb myaddCda db int iaplusb myaddCia ib cout ltlt 3double ab ltlt daplusb ltlt quotn cout ltlt int ab ltlt iaplusb ltlt quotn return 0 inc1ude ltiostreamgt u51ng namespace std 5355 int myaddCint a int b A V v cout quot I me A mm a H ltlt 1n integer myaddn a ere we break return ab doub1e myaddCdoubie a doub1e b t rLJIEBES r cout ltlt quotan doubie myaddn urn a purpose demonstrate function over39loading 39 rIC ajlr1SJ this second definition wiii confuse the compiier as we are trying to over1oad myadd based on return type int myaddCdoubie a doubie b cou ltlt quotin double myaddn return intab he compiler int mainCint argc char argv doubie da 12 db 32 39 ia 2 ib 1 double dap1usdb myaddCda db int iap1usib myaddCia ib iap1usdb myaddCia db ambiguous ltlt qoubie ab ltlt dap1usdb ltlt quot quot39 ltlt int ab ltlt iapiusib ltlt quotn 39 eturn 0 Compiler Error Messages mybadoverioad mybadoverioad mybadoverioad mybadoverioad mybadoverioad mybadoverioad badoverioad jungie I cpp In cpp18 cpp1l cpp In cpp32 cpp6 cpp18 jungie g o mybadoverioad mybadoverioadcpE unction int myaddCdou 1e doubiequot rror 39 quot rror unct rror ote ote new deciaration int myaddCdoubie doubie ambiguates 01d deciaration doubie myaddCdoubie doubie ion int mainCint char39 caii of overioaded myaddCintamp doub1eamp39 is ambiguous candidates are int myaddCint int int myaddCdoubie doubie Introduction to C Part 4 Lecture 23 CAAM 420 Fall 2004 Class Exercise Create a C class mycomplex It should store a complex number which consists of a real and a complex part use a double for each Use the mydouble I already constructed as a guide httpwwwcaamriceeducaam420SourceCmydoublestrinqh httpwwwcaamriceeducaam420SourceCmydoublestrinqcpp Implement addition subtraction multiplication and division operators Implement constructors Implement print function Test Cases 1 Given a 1230i b12 3i 1 compute cab 2 compute dabc 3 compute eabaa 4 compute fsina Introduction to C Part 1 Lecture 20 CAAM 420 Fall 2004 C Check out httpwwwcpluspluscom and httpwwwcpluspluscomdoctutorial C was first developed by Bjarne Stroustrup from Bell Labs It is based on C language and the good news is that most C programs can be compiled by a C with very few changes The way I suggested to program in C was biased towards the day we start coding in C stressed an object oriented approach ie I focused on the creation of C structs and how to create an interface to them which associated functionality with the struct recall dmat and the dmat constructor setentry getentry and linear algebra operations hello world he inputoutput facilities in C have been extended and made more intuitive his program is the C version of hello world Notice include ltstdiohgt is replaced with include ltiostreamgt u Notice printf is gone and replaced with cout ltlt 1 purpose first program in C 6 comments can now be started with two siash signs iostream can be used instead of stdioh 1nclude ltiostreamgt main interface same as before int mainCint argc char argv declare we are going to use the cout stream ustng stdcout same as printf heiio worid from Cnquot cout ltlt quotheiio worid from Cn return 0 More Complicated Output ere I include ltfstreamgt and declare that we are using the standard namespace more about that ater hen I use an ofstream constructor to build an object myoutfile of class type ofstream this is like fopen hen I use ltlt to pipe concatenated strings and variables to the myoutfile class this is like fprintf Finally I tell the object to close the file like fclose Notice that mediation with the file is performed through interface functions directly built into the class purpose demonstrate file based output include ltfstreamgt u51ng namespace std int mainCint argc char argv int n construct anoutput file object ofstream myoutfilequotmyf11etxt output first 10 integers to file fornlnlt10n myoutfile ltlt another integer ltlt n ltlt quotnquot my utfileclose return 0 Compiling and Running On rufowlnet instead of using gcc we use g to compile C files Other possible compiler names include CC c We will use cpp to denote the file is a C file eg foocpp Some people use 0 capital C or cc You can create a rule for cpp files in a Makefile to replace or complement the c file rule Compiling cont jungie Jung1e Jung1e iung1e iung1e jung1e another another another another another another another another another another jung1e g o myofstream myofstreamcpp myofstream cat myfi1etxt integer integer integer integer integer integer integer integer integer integer HNm tankOMOOO39h I C C class One of the main strengths of C is the class system A class is essentially a beefed up struct The coder is given the option to restrict which classes can access variables contained in a class using the keywords private protected and public httpwwwcpluspluscomdoctutorialtut41html Example Class Prototype We now have the ability to create our own implementation of Here is a simple class definition class mydouble private double value char name public mydouble default constructor mydoubleCdouble a char aname constructor mydoubleCconst mydouble ampa copy constructor mydouble destructor mydouble operatormydouble b return this objectb I mydouble operatormydouble b return this obJectb mydouble operatormydouble b return this obJectb mydouble operatormydouble b return this objectb void printC print this object to screen Example Class Prototype ciass mydoubie private double value char name stored variables access controlled A public mydoubieC mydoubieCdoubie a char aname mydoubleCconst mydouble ampa mydouble constructors and destructor mydoubie operatormydoub1e b return return return return operatorCmydoub1e b operatormydoubie b operatormydouble b mydoubie mydouble mydouble algebraic operators we intend to overload void printC this this this this defauit constructor constructor copy constructor destructor objectb oblectb oblectb objectb print this object to screen We now have control over how the contents of mydouble objects are set and how they interact with each other under algebraic operations Before Seeing the Implementation of the Class Member Functions Letsloo k at a piece of code which uses objects from this class 1 2 3 we use the constructor to build a and b this takes quite a few steps 1 we pass b by copy to a 2 we use a to compute ab 3 a returns a temporary ab 4 finally c gets set to the returned variable from a quite complicated but automatically taken care of int mainCint argc char argv mydouble a 20 quota I mydouble b 32 b mydouble c ab cprint mydouble Constructors The first member function to be written should be the default constructor this takes care of the following type of declaration mydouble a Here l have added a constructor which builds a mydouble given a double and a string with the intended name of the but we will use a 39Fancy mydouble class include mydoubleh default constructor mydoublemydouble printf mydoublemydouble default constructornquotl 0 strdup default value name constructor mydoublemydoubledouble a char aname printf mydoublemydouble building sn aname name strdupCaname Copy Constructor amp Destructor pically a user might wish to issue the following command mydouble a This means create b as a copy of a This is known as a copy constructor en a class object goes out of scope C automatically calls the destructor or the class this should free up any storage which was allocated for the object mydo val copy constructor char newnameBUFSIZ sprtnthnewname quotcopys aname printf mydoublemydouble copying sn aname name destructor mydoublemydouble printf mydoublemydouble deleteing sn name ifnameNULL freeCname f release the storage for name ublemydoubleconst mydouble ampa strduanewname duplicate name of a ue avalue copy value from a Abbrf evlriL25 22t i operators mydouble mydoubleoperator mydouble char newnameEBUFSIz spr1ntfnewname s squot name mydoubte cva1uebva1ue newname We can determine the behavior of multiplication division subtraction and addition by overloading these operators for this class there are other customizable operators too Here we have overloaded these operators and have made sure that the created objects have names which show how they were created Finally I added a print function so we can see what is stored in a mydouble object return C mydouble mydoubieoperatormydouble char newnameEBUFSIZ spr1nthnewname s squot name mydoubte cva1uebva1ue newname return C mydoub1e mydoubleoperator mydoub1e chaf newnameEBUFSIZ spr1nthnewname s I s name mydoubie cvalue bva1ue newname return C mydoub1e mydoubTeoperatormydoub1e char newnameBUFSIz spr1ntfltnewname s squot name mydoubte cva1uebva1ue newname return C void mydoubleprint fprinthstdout s 1fnquot name b bname b bname b bname b bname va1ue Running just building cab Usual g o mydouble mydoublecpp ungle g o mydouble mydoublecpp Jungle jungle myd0uble mydoublemyd0uble building a mydoublemydouble building b mydoublemydouble copying b mydoublemyd0uble building a copbeD mydoublemydouble delete1ng c0pyb a copbe l200000 mydoublemyd0uble deleteing a copbe mydouble a 20 quot3 mydouble b3 2 3 mydouble c ab TTTT cprint mydoublemyd0uble deletejng b C garbage collectlon 39 mydouble mydoub1e delete39l ng a jungle I Quite a few of these calls are being created because we are passing by copyl Ullding c and d jung1e Jung1e mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub mydoub mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub39 mydoub mydoub39 mydoub1e mydoub1e bu11ding b mydoub1e copying b mydoub1e building a copbe mydoub1e deTete1ng copbe mydoub1e copying b bu11d1ng a copbeDD bu11d1ng a a copbeDDD copying a copyb building Ca a copbeDDD copya copbeDDDD copy1ng a budejng b copyCa bu11d1ng a a copbeDDD copyCCa copbeDDDD b copyCaDDD copy1ng a bu11d1ng Ca a copbeDDD copyCCa copyb b copyCaDD copyCaDD de1ete1ng copyCa d918t9ing Ca a COPYCbDDD COPYCCE COPYCb b COPyCaDD deTeteing b copyCa deTeteing deTeteing deWetejng de1ete1ng G Q 3 O 39U gt E mydoub1e mydoub1e mydoub1e mydoub1e mydoub1e mydoub1e mmmmmmmmmma 110101 myd0ub1e mydoub1e mmmmmm D copyCCa copbeDDDD I mydoub1e mydoub1e mydoub39 mydoub1e deWete1ng mydoub39emydoub1e de1eteing Ca copbe 1200000 Ca a CUPbeDDD CQPVCCa COPbeDDDD Cb COPyCaDJD COPYCEDD 7 040000 mydoubWemydoub1e deTete1ng CCa a copbeDDJ copya copyb b copyCaDDD copyCa mydoubemydoub1e deTeteing a copbeD mydoub1e mydoub1e de1eteing b mydoubWemydoub1e deWeteing a jung1e I as 6 V 66 Class Exercise Download mydoublecpp and mydoubleh Using the mydouble class compute 3142314231 174231311717 How many operations does each take Preparation Read httpwwwcpluspluscomdoctutoriaItut41html Read httpwwwcpluspluscomdoctutorialtut2 3html pay specific attention to passing by reference Introduction to C Part 3 Lecture 22 CAAM 420 Fall 2004 This Lecture Returning a reference of a variable Using const to qualify a function argument Allocating arrays in C Deallocating arrays in C Class hierarchy Inheritance Polymorphism Pure virtual member functions Returning a Variable by Reference We have seen the role of passing a variable by reference recall void foodouble ampa a32 allows foo to change a for the calling function We can also allow a function to return a variable by reference The notation in this prototype double ampfoodoube bar lmplies that foo is going to return a reference to a double Return by reference Here we keep a value variable in the private part of the mydouble class However we create two access functions reference and copy The copy member returns the value variable by copy so the function calling this member function can read the value of a mydouble The reference member function returns the value variable by reference so the function calling reference can read and change the value variable of a mydouble directly cl ass mydouble private double value string name public int mainint argc char mydoubleCconst double a string aname name aname value 21 double copy return value double ampreference return value void printC H H cout ltlt name ltlt ltlt value ltlt n argv mydouble a3 a read value of a double acopy acopy acopy 3 aprint read value of a by reference double amparef areference aref 2 aprintC return 0 Return by reference cont int mainCint argc char argv mydouble a3 a read value of a Changing the copy of value double acopy acopyO gt acopy does not Change the original aprquotintO read value of a by reference Changing the reference to double amparef a reference gt aref 2 value does Change the original apr intO return 0 e Fl myreturnayrelerenceepp Jung e Jungle g o myreturnbyreference myreturnbyreferencecpp ung e gungle myreturnbyreference a3 a 2 Jungle I Usinq const to Indicate a Class Will Not Be Changed by a Specific Member Function The copy member function does not change the contents of the mydouble class mydouble We can make this explicit by private double value modifying the prototype string name We can change public mydoubleCconst double a string aname name aname value a double copy return value return value to gouble ampreferenceO double copy const return value return value void printo cout ltlt name ltlt ltlt value ltlt n double copy const Now the compiler knows that copy is not going to change the contents of the mydouble Using const to Qualify A Function Argument We can also qualify a function argument with the qualifier const which indicates to the compiler that this argument and its contents if it s a class will not be changed by the function void copierconst mydouble ampa mydouble ampb breference acopy We had to be careful to make sure that the copy member function is a const function ie we promised that the copy member will not change a OthenNise we could have sneaked in an operation which changed the contents of a which is not allowed given our declarataion of a as a const mydouble Example mmajung1e g o myreturnbyreference myreturnbyreferencecpp mange jung1e Jung1e myreturnbyreference a 3 a 2 void mydoubTecopierCconst mydoub1e ampa mydoub1e ampb b2 Jung1e I int mainCint argc char argv mydoub1e a3 a mydoub1e b2 bquot breference ac0py read va1ue of a doub1e acopy ac0py acopy 3 We have avoided passing by aPrintO copy L read va1ue of a by reference doub1e amparef areference aref 2 aprint COB va1ue of a to b mydou ecopierCab bprint return 0 re erence C a I Pointer to a Pointer A pointer to a pointer is a variable which contains the address ie location in memory of a pointer We can dereference a pointer twice to access the memory A or AO performs the first dereference to read the pointer The second dereference A or AOO Example double A 12 double ptrA ampA pointer to A double ptrptrA ampptrA pointer to the pointer to A ptrA 20 sets A to 20 ptrptrA 30 sets A to 30 Class Hierarchy Recall the previous dmat and spmat examples The matrix of doubles dmat and the sparse matrix of doubles spmat are examples of implementations which have the same purpose namely storing accessing and operating as a matrix but we used a very different implementation and representation for each type of matrix A useful feature of C is to create a base class which includes member functions common to a set of derived classes In the above case we can create a base class called for simplicity matrix with a set of universal member functions Then we will create two derived classes dmatrix and spmatrix which inherit variables from the base class The derived classes can include extra variables not in the base class Access Control private public protected private variables and functions in a class are only accessible to objects of the same class type protected variables and functions in a class are only accessible to objects of the same class type and objects derived from the same class type public variables and functions in a class are accessible to all A Simple Class Hierarchy ncolumns matrix no storage for entries nrows I dmatrix include storage for all entries I I spmatrix only store nonzeros I xample Class Prototypes ciass matrix protected int nrows nco1umns string name status pubiic set entrg virtuai dou 1 get entry virtuai dou 1 eneric printing routine voi printC base Class for writing an entry gperator e ampoperator1nt row int coumn0 for reading an entry qperator e operator1nt row int co1umn const0 ciass dmatrix private matrix private doubie 1Vdptr pubiic dmatrix dmatr1xint Nrows int Ncoiumns dmatr1x get entry for writing operator dou 1e ampoperatorint row int column get entry for reading operator ou 1e operatorint row int coiumn const string name derived Classes class spmatrix private matrix private entry entries int Nentries pubiic spmatrix I spmatrixCint Nrows int Ncoiumns string name spmatriXC get entry for writing operator dou 1e ampoperatorint row int coiumn et entry for reading operator iou 1e operatorint row int coiumn const cont In this class both dmatrix and spmatrix are derived from the matrix base class The derived classes both gain the variables from the matrix class ie they gain nrows ncolumns name and status Both derived classes also gain the member functions from the base class For example the matrix class has an associated print member function which derived classes will be able to call although we will have to implement the print function to work for all derived classes to make sense of this arrangement The base class does not implement the operator access member functions virtual ampdouble operatorint int O is the definition of a pure virtual function which has no explicit definition ie will have to be implemented by derived classes Each derived class implements its own versions of the access functions This is necessary because of the different way these two matrices are stored Allocatinq Arrays Usinq new Using passing by reference we no longer need to pass variables by pointer to a function However there is still a legitimate use of pointers when we wish to create arrays of variables Previously we used calloc to create an array of doubles specifically for the entries in a matrix There is a new function Using new to Allocate an Array Here we use dptr new doubleNrowsNcolumns to allocate an array pointed to by dptr Notice we had to go through entry by entry and zero out the allocated memory not done by default dmatrixdmatrixint Nrows int Ncolumns string newname name newname Status quotallocatedquot set dimensions in this dmatrix nrows Nrows ncoiumns Ncolumns allocate an array of NrowsNc01umns doubles ptr new doub eNrowsNcolumns forCint rowlrowltnrowsrow forCint column1columnltncolumnscolumn operatorCrowcoiumn 0 Deallocatinq Memory Usinq delete To release the allocated memory for example in the dmatrix destructor we can invoke the delete operator dmatrixdmatrix isztatus aiiocated delete dptr Here I keep a string flag which determines if an array had been allocated If it had been set to allocated I then invoke the delete operator Class Time The remainder of class will be dedicated to answering questions on the homework due today If you completed the homework download the very simple MatrixClass tarball Uncompress it and examine the inter relationships of the matrix spmatrix dmatrix classes


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.