1
1
# # Put comments here that give an overall description of what your
2
2
# # functions do
3
3
4
- # # Write a short comment describing this function
4
+ # # Write a short comment describing this function:
5
5
# #There are two functions makeCacheMatrix,makeCacheMatrix
6
6
# #makeCacheMatrix consists of set,get,setinv, getinv
7
7
# #library(Mass) is used to calculate inverse for non squared as well as squared matricies
8
8
9
9
library(MASS )
10
10
makeCacheMatrix <- function (x = matrix ()) {
11
11
inv <- NULL # initializing inverve as NULL
12
- set <- function (y ) {
12
+ set <- function (y ){
13
13
x <<- y
14
- inv <<- NULL
15
- }
16
- get <- function () x # function to get matrix x
17
- setinv <- function (mean ) inv <<- inverse
18
- getinv <- function () {
14
+ inv <<- NULL
15
+ }
16
+ get <- function ()x # function to get matrix x
17
+ setinv <- function (inverse ) inv <<- inverse
18
+ getinv <- function (){
19
19
inver <- ginv(x )
20
- inver %% x # function to obtain inverse of the matrix
20
+ inver %*% ( x ) # function to obtain inverse of the matrix
21
21
}
22
22
list (set = set , get = get ,
23
23
setinv = setinv ,
@@ -28,16 +28,40 @@ makeCacheMatrix <- function(x = matrix()) {
28
28
# # Write a short comment describing this function
29
29
# #This is used to get the cache data
30
30
31
- cacheSolve <- function (x , ... ) # #gets cache data
31
+ cacheSolve <- function (x ,... ) # #gets cache data
32
32
{
33
33
inv <- x $ getinv()
34
34
if (! is.null(inv )){ # checking whether inverse if Null
35
- message(" getting chached data!" )
36
- return ( inv ) # returns inverse value
35
+ message(" getting chached data!" )
36
+ return ( inv ) # returns inverse value
37
37
}
38
38
data <- x $ get()
39
39
inv <- solve(data ,... ) # calculates inverse value
40
40
x $ setinv(inv )
41
41
inv # # Return a matrix that is the inverse of 'x'
42
42
}
43
+
44
+ # #testing code:
45
+
46
+ > f <- makeCacheMatrix(matrix (1 : 8 ,2 ,4 ))
47
+ > f $ get()
48
+ [,1 ] [,2 ] [,3 ] [,4 ]
49
+ [1 ,] 1 3 5 7
50
+ [2 ,] 2 4 6 8
51
+
<
8EF6
td data-grid-cell-id="diff-17f1cd87465b0b799fd74a20eed65a58a1c7f356d21dd1f500aa88eb4e6330ec-42-52-1" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionNum-bgColor, var(--diffBlob-addition-bgColor-num));text-align:center" tabindex="-1" valign="top" class="focusable-grid-cell diff-line-number position-relative left-side">52
+ > f $ getinv()
53
+ [,1 ] [,2 ] [,3 ] [,4 ]
54
+ [1 ,] 0.7 0.4 0.1 - 0.2
55
+ [2 ,] 0.4 0.3 0.2 0.1
56
+ [3 ,] 0.1 0.2 0.3 0.4
57
+ [4 ,] - 0.2 0.1 0.4 0.7
58
+
59
+ > cacheSolve(f )
60
+ getting chached data !
61
+ [,1 ] [,2 ] [,3 ] [,4 ]
62
+ [1 ,] 0.7 0.4 0.1 - 0.2
63
+ [2 ,] 0.4 0.3 0.2 0.1
64
+ [3 ,] 0.1 0.2 0.3 0.4
65
+ [4 ,] - 0.2 0.1 0.4 0.7
66
+
43
67
0 commit comments