Skip to content

Commit 7f4975b

Browse files
committed
Coded
1 parent 7f657dd commit 7f4975b

File tree

1 file changed

+57
-6
lines changed

1 file changed

+57
-6
lines changed

cachematrix.R

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,66 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
##
2+
## This is a pair of functions that work together to create and cache an
3+
## inverted matrix.
4+
## - makeCacheMatrix
5+
## - cacheSolve
6+
##
7+
## A matrix is added to che cache with makeCacheMatrix. The inverse is
8+
## either computed and stored in the cache or retrieved from the cache
9+
## with the cacheSolve function.
10+
##
11+
## Example:
12+
##
13+
## a <- matrix(1:4, 2, 2)
14+
## b <- makeCacheMatrix(a)
15+
## --- Now compute the inverse for the first time and store in c
16+
## c <- cacheSolve(b)
17+
## --- Do other stuff
18+
## --- Retrieve the cached inverse matrix
19+
## c <- cacheSolve(b)
320

4-
## Write a short comment describing this function
521

6-
makeCacheMatrix <- function(x = matrix()) {
22+
## makeCacheMatrix - Create an object to compute and cache a matrix inverse
23+
##
24+
## Parameters
25+
## x - The matrix to take the inverse of
26+
##
27+
## Returns an object (list of functions) that can be used by the cacheSolve
28+
## to conpute and cache the inverse of the matrix.
29+
##
730

31+
makeCacheMatrix <- function(x = matrix()) {
32+
inv <- NULL
33+
set <- function(y) {
34+
x <<- y
35+
inv <<- NULL
36+
}
37+
get <- function() x
38+
setinv <- function(i) inv <<- i
39+
getinv <- function() inv
40+
list(set = set, get = get, setinv = setinv, getinv = getinv)
841
}
942

1043

11-
## Write a short comment describing this function
44+
## cacheSolve - Compute and cache the inverse of a matrix held in an object
45+
## created by makeCacheMatrix
46+
##
47+
## Parameters
48+
## x - The object created by makeCacheMatrix that contains the matrix
49+
##
50+
## Returns the inverse of the matrix as calculated by the solve) function.
51+
## This result may have been cached on a previous call.
52+
##
1253

1354
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
55+
## Return a matrix that is the inverse of 'x'
56+
i <- x$getinv()
57+
if(!is.null(i)) {
58+
message("getting cached data")
59+
return(i)
60+
}
61+
message("computing inverse")
62+
data <- x$get()
63+
i <- solve(data, ...)
64+
x$setinv(i)
65+
i
1566
}

0 commit comments

Comments
 (0)