Skip to content

Commit 67820d1

Browse files
committed
Submit solution
1 parent 7f657dd commit 67820d1

File tree

1 file changed

+41
-6
lines changed

1 file changed

+41
-6
lines changed

cachematrix.R

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## To speed performing repeated inversions of matrices, the functions
2+
## below will cache the first inversion and return the contents
3+
## of the cache for repeated calls.
34

4-
## Write a short comment describing this function
5+
## Creates a list that has functions to set a matrix, get the matrix,
6+
## set the inverse of the matrix, and get the inverse of the matrix.
57

68
makeCacheMatrix <- function(x = matrix()) {
7-
9+
inverse <- NULL
10+
set <- function(y) {
11+
x <<- y
12+
inverse <<- NULL
13+
}
14+
get <- function() x
15+
setinverse <- function(i) inverse <<- i
16+
getinverse <- function() inverse
17+
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
818
}
919

1020

11-
## Write a short comment describing this function
21+
## Computes the inverse of a "matrix" object created by makeCacheMatrix.
22+
## If the inverse has already been calculated, it will be returned
23+
## from the cache.
1224

1325
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
26+
inverse <- x$getinverse()
27+
if(!is.null(inverse)) {
28+
message("getting cached data")
29+
return(inverse)
30+
}
31+
data <- x$get()
32+
inverse <- solve(data, ...)
33+
x$setinverse(inverse)
34+
inverse
1535
}
36+
37+
## My test of the functions:
38+
#
39+
# > source("cachematrix.R")
40+
# > mcm <- makeCacheMatrix(x=matrix(c(4,7,2,6), nrow=2, ncol=2, byrow=T))
41+
# > cacheSolve(mcm)
42+
#[,1] [,2]
43+
# [1,] 0.6 -0.7
44+
# [2,] -0.2 0.4
45+
# > cacheSolve(mcm)
46+
# getting cached data
47+
#[,1] [,2]
48+
# [1,] 0.6 -0.7
49+
# [2,] -0.2 0.4
50+

0 commit comments

Comments
 (0)