【问题标题】:Manually multiplying two matrices in R在 R 中手动将两个矩阵相乘
【发布时间】:2019-04-24 19:21:42
【问题描述】:

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

在以下源代码中:

# 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) 
}

mat1 <- matrix(c(1,2,3,4), nrow = 2, ncol=2)    
power1 <- matrixMul(mat1)

根据矩阵乘法规则,期望的输出是:

7    10
15   22

但是,我得到以下输出:

3    12
6    16

我在这里做错了什么?

这是一种有效的乘法方法吗?

【问题讨论】:

  • R 具有使用 %*% 的内置矩阵乘法。这可能比使用 for 循环更简单。例如:mat1 %*% mat1

标签: r matrix-multiplication


【解决方案1】:

在您的代码中,您忘记对您的产品求和。应该是

mult1 &lt;- sum(vec1 * vec2)

也许在您的R 版本中,它只是分配向量的第一个元素。

【讨论】:

    【解决方案2】:

    好的。我找到了解决方案。

    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] <- sum(mult1)
        }
      }
    
      return(matOut) 
    }
    
    
    mat1 <- matrix(c(1,2,3,4), nrow = 2, ncol=2)
    mult1 <- matrixMul(mat1)
    mult1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      相关资源
      最近更新 更多