Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 42 additions & 14 deletions cachematrix.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,28 @@ https://www.coursera.org/learn/r-programming/discussions/weeks/3/threads/ePlO1eM

R session:

> # Matrices for testing the R functions
> # makeCacheMatrix and cacheSolve
> # in the Coursera R Programming Course
> #
> # First,
> # If you haven't read Leonard Greski's invaluable
> # [TIPS] Demystifying makeVector() Post
> # be sure to do so.
> #
> # A simple matrix m1 with a simple matrix inverse n1
> # Define
>makeCacheMatrix <- function(x = matrix()) {
inv <- NULL

# Set the matrix
set <- function(y) {
x <<- y
inv <<- NULL
}

# Get the matrix
get <- function() x

# Set the inverse
setInverse <- function(inverse) inv <<- inverse

# Get the inverse
getInverse <- function() inv

# Return a list of methods
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
}

> m1 <- matrix(c(1/2, -1/4, -1, 3/4), nrow = 2, ncol = 2)
> m1
[,1] [,2]
Expand Down Expand Up @@ -85,8 +96,25 @@ R session:
> #
> myMatrix_object <- makeCacheMatrix(m1)
>
> # and then
> # cacheSolve(myMatrix_object)
> cacheSolve <- function(x, ...) {
# Check if the inverse is already calculated
inv <- x$getInverse()

if (!is.null(inv)) {
message("getting cached data")
return(inv)
}

# Calculate the inverse
mat <- x$get()
inv <- solve(mat, ...)

# Store the inverse in the cache
x$setInverse(inv)

inv
}

>
> # should return exactly the matrix n1
> cacheSolve(myMatrix_object)
Expand Down Expand Up @@ -117,4 +145,4 @@ getting cached data
[,1] [,2]
[1,] 3 7
[2,] 1 5
>
>