Skip to content

Commit a2017c7

Browse files
KaramcseKaramcse
Karamcse
authored and
Karamcse
committed
Caching the inverse of a Matrix
1 parent e4eed41 commit a2017c7

File tree

1 file changed

+61
-7
lines changed

1 file changed

+61
-7
lines changed

cachematrix.R

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,69 @@
1-
## Put comments here that give an overall description of what your
2-
## functions do
31

4-
## Write a short comment describing this function
52

6-
makeCacheMatrix <- function(x = matrix()) {
73

8-
}
4+
## makeCacheMatrix create list of fuction to set matrix and get matrix and
5+
## set solve for Matrix and get the solve matrix
6+
7+
## Create square Matix
8+
## minv<-matrix(c(3,2,5,6),nrow=2,ncol=2)
99

10+
## cacheMat<-makeCacheMatrix(minv)
1011

11-
## Write a short comment describing this function
12+
##cacheMat$setMat()------> Set Matrix value
13+
##cacheMat$getMat()------> get Matrix value
14+
##cacheMat$setSolve()----> set Solve Matrix
15+
##cacheMat$getSolve()----> get Solve matrix
16+
17+
makeCacheMatrix <- function(x = matrix())
18+
{
19+
## Set the value of the matrix which we pass through y, it will store
20+
## in x (lexical scoping)
21+
22+
sol <- NULL
23+
setMat <- function(y)
24+
{
25+
x <<- y
26+
sol <<- NULL
27+
}
28+
29+
## Get the value of the matrix x that store in setMat
30+
getMat <- function() x
31+
32+
## Set the solve function
33+
setSolve <- function(solve) sol <<- solve
34+
35+
## store solve matrix value
36+
getSolve<- function() sol
37+
list(setMat = setMat, getMat = getMat, setSolve = setSolve,
38+
getSolve= getSolve)
39+
40+
}
41+
## CacheSolve returns the value of solve matrix
42+
## cacheSolve(cacheMat) contains all the list function created in cacheMat
43+
## cacheSolve(cacheMat) -------> returns inverse of matrix
1244

13-
cacheSolve <- function(x, ...) {
45+
cacheSolve <- function(x, ...)
46+
{
47+
sol <- x$getSolve()
48+
49+
## if the solve function empty it returns
50+
## function (a, b, ...)
51+
## UseMethod("solve")
52+
## <bytecode: 0x0000000007de45d0>
53+
## <environment: namespace:base>
54+
55+
if(!is.null(sol)) {
56+
message("getting cached data")
57+
return(sol)
58+
}
59+
data <- x$getMat()
60+
61+
## solve(a, b, ...) is default. But we are going to compute for square matrix
62+
## solve(a=data) is used for inverse of square matrix
63+
64+
sol <- solve(data, ...)
1465
## Return a matrix that is the inverse of 'x'
66+
x$setSolve(sol)
67+
sol
68+
1569
}

0 commit comments

Comments
 (0)