Search code examples
rmathmatrixoperation

R: Subtract A[i,] from each row B[i,]


How can I perform a simple matrix operation in R to find matrix 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)

Thanks for your time! Much appreciated! :)


Solution

  • Following is the solution:

    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)
    

    The above code produce the following output:

    > 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
    

    Hope this works for you :)