Skip to content

Commit 389d055

Browse files
committed
Adding solution for the programming assignment
1 parent 7f657dd commit 389d055

File tree

1 file changed

+37
-6
lines changed

1 file changed

+37
-6
lines changed

cachematrix.R

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,46 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly
32

4-
## Write a short comment describing this function
3+
## This function creates a special "matrix" object that can cache its inverse.
54

65
makeCacheMatrix <- function(x = matrix()) {
7-
6+
m <- NULL
7+
set <- function(y) {
8+
x <<- y
9+
m <<- NULL
10+
}
11+
get <- function() x
12+
setinverse <- function(inverse) m <<- inverse
13+
getinverse <- function() m
14+
list(set = set, get = get,
15+
setinverse = setinverse,
16+
getinverse = getinverse)
817
}
918

1019

11-
## Write a short comment describing this function
20+
## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
21+
## If the inverse has already been calculated (and the matrix has not changed),
22+
## then cacheSolve should retrieve the inverse from the cache.
23+
### This is a bit dumb cache, as it doesn't take into consideration that '...' arguments that might have changed in the second call
24+
### and returns the first value, even though calling solve with extra arguments would error
25+
### e.g. solve(my_matrix, mean)
26+
### This function computes the inverse of the special "matrix" returned by makeCacheMatrix above.
27+
### If the inverse has already been calculated (and the matrix has not changed), then cacheSolve should retrieve the inverse from the cache.
28+
### whereas:
29+
### cached = makeCacheMatrix(my_matrix)
30+
### cacheSolve(cached) gives an inverse
31+
### cacheSolve(cached, mean) second call gives the same result even though it should normally error
32+
### The solution would be to either hash all arguments or store them in a list that would be a key for getting cached martices,
33+
### but that is beyond this programming assignment.
1234

1335
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
36+
## Return a matrix that is the inverse of 'x'
37+
m <- x$getinverse()
38+
if(!is.null(m)) {
39+
message("getting cached data")
40+
return(m)
41+
}
42+
data <- x$get()
43+
m <- solve(data, ...)
44+
x$setinverse(m)
45+
m
1546
}

0 commit comments

Comments
 (0)