Skip to content

Commit c8fd347

Browse files
author
John Kinsella
committed
Checking in code for programming assignment 2.
1 parent 7f657dd commit c8fd347

File tree

1 file changed

+48
-7
lines changed

1 file changed

+48
-7
lines changed

cachematrix.R

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,56 @@
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+
## cachematrix - R functions to compute and cache inverse of a Matrix
2+
##
3+
## Written by John Kinsella for Coursera class "R Programming"
4+
##
55

6+
## Function representing a matrix object
7+
## capable of caching it's inverse value
8+
##
9+
## Usage:
10+
## myMatrix <- makeCacheMatrix(x)
11+
## Arguments:
12+
## x - matrix value to initially store
13+
## Returns:
14+
## Returns a list of 4 functions related to the matrix:
15+
## * set(newValue) - set new value for matrix
16+
## * get() - get the current matrix value
17+
## * setInverse(inverseMatrix) - set the inverse matrix value
18+
## * getInverse() - get the inverse of current matrix if set, NULL otherwise
619
makeCacheMatrix <- function(x = matrix()) {
20+
inverseMatrix <- NULL
21+
22+
set <- function(newValue) {
23+
x <<- newValue
24+
inverseMatrix <<- NULL
25+
}
26+
get <- function() x
27+
setinverse <- function(targetInverse) inverseMatrix <<- targetInverse
28+
getinverse <- function() inverseMatrix
729

30+
list(set=set, get=get, setinverse=setinverse, getinverse=getinverse)
831
}
932

33+
## Computes inverse of matrix. If inverse was already calculated, returns cached
34+
## value.
35+
##
36+
## Usage:
37+
## invertedMatrix <- cacheSolve(x)
38+
## Arguments:
39+
## x - list generated by makeCacheMatrix()
40+
## Returns:
41+
## inverted version of matrix in x.
42+
cacheSolve <- function(x, ...) {
43+
inverseMatrix <- x$getinverse()
1044

11-
## Write a short comment describing this function
45+
# If matrix inverse has been calculated, returned cached value
46+
if(!is.null(inverseMatrix)) {
47+
message("Getting cached data")
48+
return(inverseMatrix)
49+
}
1250

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
51+
# If not cached already, calculate inverse and return
52+
data <- x$get()
53+
inverseMatrix <- solve(data)
54+
x$setinverse(inverseMatrix)
55+
inverseMatrix
1556
}

0 commit comments

Comments
 (0)