Skip to content

Commit 07026f8

Browse files
committed
added function body to makeCacheMatrix and cacheSolve
1 parent 7f657dd commit 07026f8

File tree

1 file changed

+40
-7
lines changed

1 file changed

+40
-7
lines changed

cachematrix.R

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,48 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## makeCacheMatrix(X = matrix()) returns a list of functions that can be uses to set or get the matrix and to set and get the cached matrix inverse
2+
## if X is passed as parameter, then the matrix is initialized with it, else an empty matrix is used
3+
## cacheSolve(x) returns the inverse of the matrix actually setted on x
4+
## if inverse cached, then just returns cached value, else calculates and caches the inverse first
5+
## x is the list of functions return by makeCacheMatrix
36

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

8+
## params
9+
## -> (optional) x should be a squared and invertible matrix. Sets the actual matrix.
10+
##
11+
## returns a list of functions
12+
## -> set(y): sets the matrix to y. Resets inverse cache.
13+
## -> get: returns the actual matrix
14+
## -> setinverse(inverse): caches the inverse of the matrix
15+
## -> getinverse: returns the cached matrix inverse
616
makeCacheMatrix <- function(x = matrix()) {
7-
17+
i <- NULL
18+
set <- function(y) {
19+
x <<- y
20+
i <<- NULL
21+
}
22+
get <- function() x
23+
setinverse <- function(inverse) i <<- inverse
24+
getinverse <- function() i
25+
list(set = set, get = get,
26+
setinverse = setinverse,
27+
getinverse = getinverse)
828
}
929

1030

11-
## Write a short comment describing this function
12-
31+
## params
32+
## -> x is the list of functions returned by makeCacheMatrix
33+
## -> ... are arbitrary parameters that could be passed to "solve" function
34+
##
35+
## returns the inverse of the matrix.
36+
## If inverse was already calculated, then it returns the cached copy, and prints a notice message "getting cached data"
1337
cacheSolve <- function(x, ...) {
1438
## Return a matrix that is the inverse of 'x'
15-
}
39+
i <- x$getinverse()
40+
if(!is.null(i)) {
41+
message("getting cached data")
42+
return(i)
43+
}
44+
data <- x$get()
45+
i <- solve(data, ...)
46+
x$setinverse(i)
47+
i
48+
}

0 commit comments

Comments
 (0)