矩阵乘法使用循环 [英] Matrix Multiplication using loop
问题描述
我有一个链式矩阵乘法问题.我只有一个输入矩阵A,将保存矩阵B<-矩阵A.需要按以下方式进行乘法
I have a matrix multiplication problem in a chain format. I only have a input Matrix A, will save Matrix B <- Matrix A. Need to multiply in the below fashion
C = B * A
D = C * A
E = D * A
A是每个月所有乘法的参考矩阵. 这个乘法链持续了18个月.
A is a reference matrix for all the multiplication for each month. this chain of multiplication taken places till 18 months.
矩阵A:
2 3
4 2
代码:
a = matrix( c(2, 3, 4, 2), nrow=2, ncol=2, byrow = TRUE)
b <- a
c <- b %*% a
d <- c %*% a
e <- d %*% a
f <- e %*% a
g <- f %*% a
每个时间A是将来与结果相乘的参考矩阵.重复了18次.
Each time A is the reference matrix for future multiplication with the result. This repeated for 18 times.
我必须手动对上述乘法进行18次校正,因此需要查找循环.
I have to manually right the above multiplication for 18 times, so looking for a loop.
预期输出:
c<-b%*%a
c <- b %*% a
c
[,1] [,2]
[1,] 16 12
[2,] 16 16
d<-c%*%a
d <- c %*% a
d
[,1] [,2]
[1,] 80 72
[2,] 96 80
e<-d%*%a
e <- d %*% a
e
[,1] [,2]
[1,] 448 384
[2,] 512 448
f<-e%*%a
f <- e %*% a
f
[,1] [,2]
[1,] 2432 2112
[2,] 2816 2432
因此应重复18次.请帮忙.提前致谢.
so this should be repeated for 18 times. Please help. Thanks in Advance.
在先前发布的问题中,逻辑是不同的.
the logic is different in the earlier question posted.
推荐答案
您可以这样做:
Mpow <- function(A, n) {
if (n==1) return(list(A))
L <- list(A)
P <- A
for (i in 2:n) {
P <- P %*% A
L[[i]] <- P
}
return(L)
}
a = matrix( c(2, 3, 4, 2), nrow=2, ncol=2, byrow = TRUE)
Mpow(a, 1)
Mpow(a, 2)
Mpow(a, 18)
您将获得矩阵幂的列表.问题中的矩阵f
是Mpow(a,5)
的最后一个元素.
这是该函数的简短变体:
You will get a list of the powers of the matrix. The matrix f
in the question is the last element of Mpow(a,5)
.
Here is short variant of the function:
Mpow <- function(A, n) {
L <- list(A)
if (n==1) return(L)
P <- A
for (i in 2:n) L[[i]] <- (P <- P %*% A)
return(L)
}
无需定义新功能,您可以执行以下操作:
Without defining a new function you can do:
n <- 5
Reduce('%*%', rep(list(a), n), accumulate=TRUE)
这篇关于矩阵乘法使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!