Skip to content

Commit 576adc5

Browse files
authored
Programming Assignment 2: Lexical Scoping
1 parent 7f657dd commit 576adc5

File tree

1 file changed

+41
-6
lines changed

1 file changed

+41
-6
lines changed

cachematrix.R

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,50 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
## Cache matrix inversion
32

4-
## Write a short comment describing this function
3+
## Create a matrix object to cache it's inverse
4+
## Example of usage cacheSolve(makeCacheMatrix(matrix(c(1, 3, 2, 4), 2,2)))
55

66
makeCacheMatrix <- function(x = matrix()) {
7-
7+
8+
m <- NULL
9+
10+
set <- function (y) {
11+
x <<- y
12+
m <<- NULL
13+
}
14+
15+
get <- function () {
16+
x
17+
}
18+
19+
setInverse <- function (inverseMatrix) {
20+
21+
if (hasArg(inverseMatrix))
22+
# Set inversed matrix
23+
m <<- inverseMatrix
24+
else
25+
# Invert current matrix
26+
m <<- solve(x)
27+
}
28+
29+
getInverse <- function () {
30+
m
31+
}
32+
33+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
834
}
935

1036

11-
## Write a short comment describing this function
37+
## Returns a matrix inverted from x
38+
## x should come from makeCacheMatrix
1239

1340
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
41+
42+
m <- x$getInverse()
43+
44+
if (is.null(m)) {
45+
m <- solve(x$get())
46+
x$setInverse(m)
47+
}
48+
49+
m
1550
}

0 commit comments

Comments
 (0)