Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f436517

Browse files
author
felix
committed
first try, seems to work :)
1 parent 7f657dd commit f436517

File tree

1 file changed

+46
-6
lines changed

1 file changed

+46
-6
lines changed

cachematrix.R

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,55 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## A pair of functions that allow cached computation of inverse matrices
2+
## Note: input matrices are assumed to be invertible
33

4-
## Write a short comment describing this function
4+
# Example Usage:
5+
#
6+
# > B <- matrix(c(2,2,3,2), ncol=2, nrow=2)
7+
# > x <- makeCacheMatrix(B)
8+
# cacheSolve(x)
9+
#
510

11+
# creates a cachematrix for an input matrix x. The result
12+
# of this function can then be passed to cacheSolve() in order
13+
# to compute the inverse of x such that repeated invocations
14+
# use a cached result.
615
makeCacheMatrix <- function(x = matrix()) {
716

8-
}
17+
# this is the cached result
18+
inverse <- NULL
19+
20+
# set the input matrix (this can be used to reuse the vector returned
21+
# by makeCacheMatrix for a different input matrix
22+
set <- function(y) {
23+
x <<- y
24+
inverse <<- NULL #make sure to clear cached result
25+
}
26+
27+
# returns the input matrix
28+
get <- function() x
29+
30+
# set the inverse matrix.
31+
setinverse <- function(i) inverse <<- i
32+
getinverse <- function() inverse
33+
list(set = set, get = get,
34+
setinverse = setinverse,
35+
getinverse = getinverse)
936

37+
}
1038

11-
## Write a short comment describing this function
1239

40+
# returns the inverse of a matrix x. x
41+
# must be a cachematrix obtained via makeCacheMatrix
1342
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
43+
44+
# did we compute the result before?
45+
result <- x$getinverse()
46+
47+
if (is.null(result)){
48+
# inverse has not been computed before, so compute it now
49+
matrix <- x$get() # this is the original input matrix
50+
result <- solve(matrix) # solve it
51+
x$setinverse(result) # cache the result in the cache matrix
52+
}
53+
54+
result # return the result
1555
}

0 commit comments

Comments
 (0)