Search code examples
rerror-handlingmatrix-multiplication

Matrix multiplication (row by row)


I have a matrix of dimension 1000x100. I want to make an inner product (of each row with itselg) row by row, so in theory I could get a vector of 1000x1. For example:

A<-matrix(c(1,2,3,4),nrow=2,ncol=2,byrow=2)
     [,1] [,2]
[1,]    1    2
[2,]    3    4

I want to get a vector that looks like this:

              [,1]
[1,]    c(1,2) %*% t(c(1,2))
[2,]    c(3,4) %*% t(c(3,4))  

I tried doing a loop, but an error occurs:

U<-matrix(nrow=1000,ncol=1)
U

k=0
for(i in 1:nrow(U_hat)){
  for(j in 1:nrow(U_hat)){
    k=k+1
    U[k,1]=U_hat[i,]%*%t(U_hat[j,])
  }
}

where U_hat is the matrix of dimension 1000x100.

I would appreciate the help to know how to do this multiplication. Thank you.


Solution

  • Multiply A by itself and take the row sums:

    rowSums(A*A)
    ## [1]  5 25
    

    This would also work:

    apply(A, 1, crossprod)
    ## [1]  5 25
    

    This would work too:

    diag(tcrossprod(A))
    ## [1]  5 25