0

I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
            x <<- y
            inv <<- NULL
    }
    get <- function() x
    setInverse <- function(inverse) inv <<- inverse
    getInverse <- function() inv
    list(set = set,
         get = get,
         setInverse = setInverse,
         getInverse = getInverse)
}

First in the function makeCacheMatrix, why does 'set function' use variable 'y'?
Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

JeongHansol
  • 3
  • 1
  • 5

2 Answers2

3

x <<- y creates x, which is then retrieved by get(). Note that get is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get function through base::get.

Line get <- function() x is a "short" version of

get <- function() {
  x
}

Short version will work if you have only one line or separate statements using ;. The biggest beef I have with this piece of code is no use of argument. This may be fine with Java or some other language, but I don't consider that an R way. Modifying objects like this can lead to unintended behavior which could lead to painstaking debugging.

setInverse and getInverse are not the same. What they do is set inverse or get it.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

You know that the goal of this task is to create a super matrix that can store it's content and it's inverse as well. So it has to have 2 variable x the matrix, and inv the inverse. Each variable has 2 functions set and get. So, set is a function that takes an argument and do something inside it, in this code set takes y as an argument (dummy variable could be any other name) and assign it to the matrix x. The same for inv.

This will make the only access for these variables is through set and get.

Note that:(R documentation) The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned

Now, if we want to use this function:

mat <- makeCacheMatrix()

## set the matrix value
mat$set(matrix(data = (1:10), nrow = 5, ncol = 2))

## Check that we stored it correctly
mat$get()
# [,1] [,2]
# [1,]    1    6
# [2,]    2    7
# [3,]    3    8
# [4,]    4    9
# [5,]    5   10
Fadwa
  • 1,717
  • 5
  • 26
  • 43