R:确定矩阵是否为正方形的函数

时间:2017-08-07 21:17:49

标签: r function if-statement

我正在尝试为coursEra上的R Programming课程运行这个例子。然而,当我试图确定矩阵是否为方形时,我得到错误说" is.square.matrix(x)中的错误:参数x不是矩阵"

我的代码如下:

library(matrixcalc)
##non-square matrix
NCols <- sample(3:6, 1)
NRows <- sample(2:8, 1)

myMat <- matrix(runif(NCols*NRows), ncol=NCols)
is.square.matrix(myMat)

## functions
makeMatrix <- function(x = matrix()) {
  m <- NULL
  set <- function(y) {
    x <<- y
    m <<- NULL
  }
  get <- function() x
  setInv <- if (is.square.matrix(x) == TRUE) {
    function(solve) m <<- solve
  }
     {
    function(ginv) m <<- ginv
  }
  getInv <- function() m
  list(x, set = set, get = get,
       setInv = setInv,
       getInv = getInv)
}

cacheMatrix <- function(x, ...) {
  m <- x$getInv()
  if(!is.null(m)) {
    message("getting cached data")
    return(m)
  }
  data <- x$get()
  m <-  if (is.square.matrix(x) == TRUE) {
    solve(data, ...)
  }
     {
    ginv(data, ...)
  }
  x$setInv(m)
  m
}

## run functions for matrix
notSquare <- makeMatrix(myMat) 
cacheMatrix(notSquare)


##check
ginv(myMat)

然后我收到错误:

  

is.square.matrix(x)出错:参数x不是矩阵

我是初学者,所以不确定如何让sentInv识别并检查矩阵是否为正方形。

布赖恩

2 个答案:

答案 0 :(得分:0)

没关系。在makeMatrix函数中用x替换x(x = matrix())并在cacheMatrix中用x替换x(data)

答案 1 :(得分:0)

这是答案。我刚刚创建了函数(x)而不是函数(x = matrix())和&#39;数据&#39;是在缓存函数中拉出矩阵的变量需要让我输入。

##non-square matrix
NCols <- sample(3:6, 1)
NRows <- sample(2:8, 1)

myMat <- matrix(runif(NCols*NRows), ncol=NCols)
is.square.matrix(myMat)

## functions
makeCacheMatrix <- function(x) {
        m <- NULL
        set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setInv <- if (is.square.matrix(x) == TRUE) {
                function(solve) m <<- solve
        }
        else {
                function(ginv) m <<- ginv
        }
        getInv <- function() m
        list(x, set = set, get = get,
             setInv = setInv,
             getInv = getInv)
}

cacheSolve <- function(x, ...) {
        m <- x$getInv()
        if(!is.null(m)) {
                message("getting cached data")
                return(m)
        }
        data <- x$get()
        m <-  if (is.square.matrix(data) == TRUE) {
                solve(data, ...)
        }
        else {
                ginv(data, ...)
        }
        x$setInv(m)
        m
}

## run functions for myMat
notSquare <- makeCacheMatrix(myMat) 
cacheSolve(notSquare)


##check
ginv(myMat)