首页 > 解决方案 > 在 R 中创建或初始化一个空矩阵

问题描述

我正在使用R v 3.0.0 (2013-04-03)RStudio v 1.1.463在 Win-7 64 位下使用。

在以下源代码中:

# Problem 1 - Matrix powers in R
#
# R does not have a built-in command for taking matrix powers. 
# Write a function matrixpower with two arguments mat and k that 
# will take integer powers k of a matrix mat.
matrixMul <- function(mat1)
{
  rows <- nrow(mat1)
  cols <- ncol(mat1)

  matOut = matrix(, nrow = rows, ncol = cols) # empty matrix

  for (i in 1:rows) 
  {
    for(j in 1:cols)
    {
      vec1 <- mat1[i,]
      vec2 <- mat1[,j]

      mult1 <- vec1 * vec2

      matOut[i,j] <- mult1
    }
  }

  return(matOut) 
}

matrixpower<-function(mat1, k)
{
  matOut <-mat1#empty matix

  for (i in k) 
  {
    matOut <- matrixMul(matOut)
  }

  return(matOut) 
}

mat1 <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol=3)

power1 <- matrixMul(mat1)

宣言

matOut <- matrix(, nrow = rows, ncol = cols) # empty matrix

甚至在编译之前给出以下语法错误:

missing argument to function call

在此处输入图像描述

我正在遵循这些说明

我在这里做错了什么?

标签: rmatrix

解决方案


试试这个:

matOut = matrix(numeric(rows*cols), nrow = rows, ncol = cols) # empty matrix

推荐阅读