Skip to content

Commit 88561f4

Browse files
committed
first version of cachematrix.R
1 parent 7f657dd commit 88561f4

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

cachematrix.R

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,90 @@
11
## Put comments here that give an overall description of what your
22
## functions do
3+
#
4+
# makeCacheMatrix creates a special "matrix", which is really a list
5+
# containing functions to
6+
#
7+
# 1 set the value of the matrix
8+
# 2 get the value of the matrix
9+
# 3 set the value of the inverse
10+
# 4 get the value of the inverse
11+
#
12+
# cacheSolve solve the inverse of the input "matrix", in the manner that
13+
#
14+
# 1. return the cached inverse if the cache is not NULL
15+
# 2. calculate the inverse with solve if the cache is NULL, set it to the cache,
16+
# and then return it
17+
#
18+
# Example:
19+
# > A<-matrix(c(1,2,3,4),c(2,2))
20+
# > B<-makeCacheMatrix(A)
21+
# > B$get()
22+
# [,1] [,2]
23+
# [1,] 1 3
24+
# [2,] 2 4
25+
# > cacheSolve(B)
26+
# [,1] [,2]
27+
# [1,] -2 1.5
28+
# [2,] 1 -0.5
29+
# > cacheSolve(B)
30+
# getting cached data
31+
# [,1] [,2]
32+
# [1,] -2 1.5
33+
# [2,] 1 -0.5
34+
#
35+
36+
337

438
## Write a short comment describing this function
39+
#
40+
# creates a special "matrix", which is really a list
41+
# of the following functions
42+
#
43+
# set(y) set y as the data of the matrix
44+
# get() : get the data of the matrix
45+
# setinverse(): set the value of the inverse
46+
# getinverse(): get the value of the inverse
47+
#
48+
# arguments:
49+
# x is a matrix to be set as the "data" of the special matrix
550

651
makeCacheMatrix <- function(x = matrix()) {
52+
inv <- NULL
53+
set <- function(y){
54+
x <<- y
55+
}
56+
get <- function() x
757

58+
setinverse <- function(inverse){
59+
inv <<-inverse
60+
}
61+
getinverse <- function() inv
62+
63+
list(set = set, get=get, setinverse = setinverse, getinverse=getinverse)
64+
865
}
966

1067

1168
## Write a short comment describing this function
69+
#
70+
# return the cached inverse and print a message,
71+
# calculate the inverse with solve and set it to the cache otherwise
72+
#
73+
# arguments:
74+
# x is a special matrix created by makeCacheMatrix
75+
# ... is the other options that will be passed to "solve"
76+
#
1277

1378
cacheSolve <- function(x, ...) {
1479
## Return a matrix that is the inverse of 'x'
80+
inv <- x$getinverse()
81+
if(!is.null(inv)){
82+
message("getting cached data")
83+
}
84+
else{
85+
data <- x$get()
86+
inv <- solve(data,...)
87+
x$setinverse(inv)
88+
}
89+
inv
1590
}

0 commit comments

Comments
 (0)