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: 47 additions & 9 deletions cachematrix.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,53 @@
## Put comments here that give an overall description of what your
## functions do

## Write a short comment describing this function
## These functions create a special matrix object that can cache its inverse
## and compute the inverse using caching for efficiency.

## makeCacheMatrix: Creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {

# Initialize the inverse as NULL
inv <- NULL

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

# Get the matrix
get <- function() x

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

# Get the inverse
getinverse <- function() inv

# Return a list of functions
list(set = set,
get = get,
setinverse = setinverse,
getinverse = getinverse)
}


## Write a short comment describing this function

## cacheSolve: Computes the inverse of the special "matrix" returned by makeCacheMatrix
## If the inverse has already been calculated (and matrix hasn't changed),
## then retrieves inverse from cache
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
# Get cached inverse
inv <- x$getinverse()

# If inverse exists in cache, return it
if(!is.null(inv)) {
message("getting cached data")
return(inv)
}

# Otherwise, compute the inverse
data <- x$get()
inv <- solve(data, ...)

# Cache the inverse
x$setinverse(inv)

# Return the inverse
inv
}