如何在R中执行简单的矩阵运算以找到矩阵C?
A = (a11 a12 a13) B = (b1) C = (a11-b1 a12-b1 a13-b1)
(a21 a22 a23) (b2) (a21-b2 a22-b2 a23-b2)
(a31 a32 a33) (b3) (a31-b3 a32-b3 a33-b3)
感谢您的时间!非常感激! :)
答案 0 :(得分:2)
只需从B
A
即可
A = matrix(c(1:9),3,3)
A
# [,1] [,2] [,3]
#[1,] 1 4 7
#[2,] 2 5 8
#[3,] 3 6 9
B = c(1:3)
B
# [,1]
#[1,] 1
#[2,] 2
#[3,] 3
C= A - B
C
# [,1] [,2] [,3]
#[1,] 0 3 6
#[2,] 0 3 6
#[3,] 0 3 6
答案 1 :(得分:1)
以下是解决方案:
a=matrix(c(1:9), nrow = 3, ncol = 3)
b=matrix(c(1:3),nrow = 3,ncol = 1)
ans=c()
for(i in 1:ncol(a)){
ans=c(ans,a[,i]-b[,1])
}
final=matrix(ans,nrow = 3,ncol = 3)
上面的代码产生以下输出:
> a
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> b
[,1]
[1,] 1
[2,] 2
[3,] 3
> final
[,1] [,2] [,3]
[1,] 0 3 6
[2,] 0 3 6
[3,] 0 3 6
希望这适合你:)