Skip to content

Commit 1552336

Browse files
committed
Program to cache the inverse of a matrix
1 parent 1dc05a5 commit 1552336

1 file changed

Lines changed: 38 additions & 21 deletions

File tree

cachematrix.R

Lines changed: 38 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,41 @@
1+
#This program keep in memory the result of an inverse of a matrix
2+
3+
#The function makeCacheMatrix create a special matrix and has 4 sub functions
14
makeCacheMatrix <- function(x = matrix()) {
2-
m <- NULL
3-
set <- function(y) {
4-
x <<- y
5-
m <<- NULL
6-
}
7-
get <- function() x
8-
setsolve <- function(solve) m <<- solve
9-
getsolve <- function() m
10-
list(set = set, get = get,
11-
setsolve = setsolve,
12-
getsolve = getsolve)
5+
m <- NULL
6+
7+
#sub function 1 set: to set the value of the matrix
8+
set <- function(y) {
9+
x <<- y
10+
m <<- NULL
11+
}
12+
13+
#sub function 2 get: to get the value of the matrix
14+
get <- function() x
15+
16+
#sub function 3 setsolve: to set the value of the inverse of the matrix
17+
setsolve <- function(solve)
18+
m <<- solve
19+
20+
#sub function 4 getsolve: to get the value of the inverse of the matrix
21+
getsolve <- function() m
22+
list(set = set, get = get,
23+
setsolve = setsolve,
24+
getsolve = getsolve)
1325
}
26+
27+
#The function cacheSolve calculates the inverse of a matrix created with the makeCacheMatrix
1428
cacheSolve <- function(x, ...) {
15-
m <- x$getsolve()
16-
if(!is.null(m)) {
17-
message("getting cached data")
18-
return(m)
19-
}
20-
data <- x$get()
21-
m <- solve(data, ...)
22-
x$setsolve(m)
23-
m
24-
}
29+
#If the inverse was calculated before, return the value
30+
m <- x$getsolve()
31+
if(!is.null(m)) {
32+
message("getting cached data")
33+
return(m)
34+
}
35+
#Else calculate the inverse of the matrix and add it to the list
36+
data <- x$get()
37+
m <- solve(data, ...)
38+
x$setsolve(m)
39+
m
40+
}
41+

0 commit comments

Comments
 (0)