Skip to content

Commit 728d96a

Browse files
author
Matteo Barbieri
committed
Assignment complete
1 parent 7f657dd commit 728d96a

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

cachematrix.R

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,43 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## These functions provide a way to cache the result of a possibly slow calculation,
2+
## such as the inverse of a matrix.
3+
## The matrix to be inverted must be inputted into the makeCacheMatrix.
4+
## Then the object returned by makeCacheMatrix must be passed to the cacheSolve
5+
## function which will return the inverted matrix (either cached or computed)
36

4-
## Write a short comment describing this function
7+
## This function creates a special "matrix" object that can cache its inverse.
8+
## Actually it's only a list of function to operate with the matrix value and
9+
## store its inverse
510

611
makeCacheMatrix <- function(x = matrix()) {
7-
12+
13+
inverse <- NULL
14+
set <- function(m) {
15+
x <<- m
16+
inverse <<- NULL
17+
}
18+
get <- function() x
19+
setinverse <- function(inv) inverse <<- inv
20+
getinverse <- function() inverse
21+
list(set = set, get = get,
22+
setinverse = setinverse,
23+
getinverse = getinverse)
824
}
925

1026

11-
## Write a short comment describing this function
27+
## This function computes the inverse of the special "matrix" returned by
28+
## makeCacheMatrix above.
29+
## If the inverse has already been calculated (and the matrix has not changed),
30+
## then the cachesolve retrieves the inverse from the cache printing a log message.
1231

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

0 commit comments

Comments
 (0)