Skip to content

Commit f756c69

Browse files
committed
Peer asignmenet
1 parent 7f657dd commit f756c69

File tree

1 file changed

+53
-8
lines changed

1 file changed

+53
-8
lines changed

cachematrix.R

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,60 @@
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+
## Perform inversion of a matrix, cache the result, and assert the cache did
2+
## work by expecting a message in console ("getting cached data")
3+
##
4+
## Then verify the inversion was computed properly by multiplying the inverted
5+
## matrix by the original matrix. Expecting an identity matrix
56

7+
## ------------------------------------------------------------
8+
## Build a list of functions to perform the cached matrix
69
makeCacheMatrix <- function(x = matrix()) {
10+
# init cached result to null
11+
m <- NULL
12+
13+
# functions
14+
setMatrix <- function(y) {
15+
x <<- y
16+
m <<- NULL
17+
}
18+
getMatrix <- function() x
19+
setMatrixInverted <- function(matrixInverted) m <<- matrixInverted
20+
getMatrixInverted <- function() m
21+
22+
# list of functions
23+
list(setMatrix = setMatrix,
24+
getMatrix = getMatrix,
25+
setMatrixInverted = setMatrixInverted,
26+
getMatrixInverted = getMatrixInverted)
27+
}
28+
29+
## ------------------------------------------------------------
30+
## Search the cache or resolve and store if the result is not in cache
31+
cacheSolve <- function(x, ...) {
32+
m <- x$getMatrixInverted()
33+
if(!is.null(m)) {
34+
message("getting data From Cache")
35+
return(m)
36+
}
37+
message("Data not found in the cache . computing ...")
38+
39+
data <- x$getMatrix()
40+
m <- inverse(data, ...)
41+
x$setMatrixInverted(m)
42+
m
43+
}
744

45+
## ------------------------------------------------------------
46+
## Doing the actual matrix inversion
47+
inverse <- function(x){
48+
solve(x) # ginv or solve
849
}
950

51+
## Apply calculation
52+
v <- cbind(c(0.5, 0.3), c(0.4, 0.9))
53+
cv <- makeCacheMatrix(v)
54+
im <- cacheSolve(cv)
55+
56+
## Verify results
57+
im <- cacheSolve(cv)
58+
print(im %*% v)
1059

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

13-
cacheSolve <- function(x, ...) {
14-
## Return a matrix that is the inverse of 'x'
15-
}

0 commit comments

Comments
 (0)