Skip to content

Commit f5219b8

Browse files
committed
Assignment 2
1 parent 7f657dd commit f5219b8

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

cachematrix.R

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
1+
# Create a CacheMatrix, a special Matrix object that can cache its inverse (available by calling getInverse)
2+
makeCacheMatrix <- function(x = matrix()) {
33

4-
## Write a short comment describing this function
4+
# Initialize inverse as null (will be calculated on demand)
5+
inverse <- NULL
6+
7+
# A set function to set the Matrix and reset the cached inverse
8+
set <- function(y) {
9+
x <<- y
10+
inverse <<- NULL
11+
}
512

6-
makeCacheMatrix <- function(x = matrix()) {
13+
# Get function to retrieve the Matrix
14+
get <- function() x
715

8-
}
16+
# Functions to set and get the cached inverse
17+
setInverse <- function(solve) inverse <<- solve
18+
getInverse <- function() inverse
919

20+
# Return list of the wrapped functions of the matrix
21+
list(set = set, get = get, setInverse = setInverse, getInverse = getInverse)
22+
}
1023

11-
## Write a short comment describing this function
1224

25+
# Check if the inverse has already been calculated for this matrix and return it if so, otherwise calculate and cache the inversex
1326
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
27+
28+
# check if the inverse has been cached already
29+
inverse <- x$getInverse()
30+
31+
if(!is.null(inverse)) {
32+
message("Using Cached inverse")
33+
# Use the cached inverse
34+
return(inverse)
35+
}
36+
37+
# Inverse not cached, calculate and cache it
38+
inverse <- solve(x$get(),...)
39+
x$setInverse(inverse)
40+
inverse
1541
}

test.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
source("cachematrix.R")
2+
3+
a <- makeCacheMatrix(matrix(1:4,2))
4+
a$get()
5+
a$getInverse()
6+
a$set(matrix(5:8,2))
7+
a$get()
8+
cacheSolve(a)
9+
cacheSolve(a)
10+
a$getInverse()

0 commit comments

Comments
 (0)