手动将R中的两个矩阵相乘

问题描述 投票:1回答:2

我在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 matrix-multiplication
2个回答
1
投票

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

mult1 <- sum(vec1 * vec2)

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


0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.