Skip to content

Commit ad92f76

Browse files
author
Gehad Wahgdy
committed
Programming Assignment 2: Lexical Scoping
1 parent 7f657dd commit ad92f76

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

cachematrix.R

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,39 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
3-
4-
## Write a short comment describing this function
1+
## Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of
2+
## a matrix rather than compute it repeatedly. Below are a pair of functions that cache the inverse of a matrix.
53

4+
## makeCacheMatrix:
5+
## This function creates a special "matrix" object that can cache its inverse.
6+
##
67
makeCacheMatrix <- function(x = matrix()) {
7-
8+
invMatrix <- NULL
9+
set <- function(y) {
10+
x <<- y
11+
invMatrix <<- NULL
12+
}
13+
get <- function() x
14+
setInverse <- function(inv) invMatrix <<- inv
15+
getInverse <- function() invMatrix
16+
list(set = set,
17+
get = get,
18+
setInverse = setInverse,
19+
getInverse = getInverse)
820
}
921

1022

11-
## Write a short comment describing this function
12-
23+
## cacheSolve:
24+
## This function computes the inverse of the special "matrix" returned by makeCacheMatrix.
25+
## If the inverse has already been calculated (and the matrix has not changed),
26+
## then cacheSolve should retrieve the inverse from the cache.
27+
##
1328
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
29+
invMatrix <- x$getInverse()
30+
if(!is.null(invMatrix)) {
31+
message("getting cached matrix")
32+
return(invMatrix)
33+
}
34+
m <- x$get()
35+
## Return a matrix that is the inverse of 'm'
36+
invMatrix <- solve(m, ...)
37+
x$setInverse(invMatrix)
38+
invMatrix
1539
}

0 commit comments

Comments
 (0)