2017-01-21 49 views
0

如何在R中執行簡單的矩陣運算來查找矩陣C?R:從每一行減去A [i,] B [i,]

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) 

感謝您的時間!非常感激! :)

回答

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 

希望這對你的作品:)

+0

完美!謝謝! – Sebbe

2

只需從A

減去 B
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 
相關問題