【发布时间】: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