Hi all, I'd like to do a multiplication between 2 matrices buy only want resulsts of cloumn 1 * column 1, column 2 * column 2 and so on. Now I do C <- diag(t(A) %*% B) Is there a bulit in way to do this? Thank you. [[alternative HTML version deleted]]
On Fri, 23 Jun 2006, Mu Tian wrote:> Hi all, > > I'd like to do a multiplication between 2 matrices buy only want resulsts of > cloumn 1 * column 1, column 2 * column 2 and so on. > > Now I do > > C <- diag(t(A) %*% B) > > Is there a bulit in way to do this?If * here means vector inner product, colSums(A*B) which is a lot more efficient.> > Thank you. > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html >-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
On Fri, 2006-06-23 at 11:53 -0400, Mu Tian wrote:> Hi all, > > I'd like to do a multiplication between 2 matrices buy only want resulsts of > cloumn 1 * column 1, column 2 * column 2 and so on. > > Now I do > > C <- diag(t(A) %*% B) > > Is there a bulit in way to do this? > > Thank you.You just want: A * B for the initial multiplication. This technically gives you element by element multiplication. Since matrices are vectors with a dim attribute and elements stored by default in column order (top to bottom, then left to right), the result matrix will yield what you require on a column by column basis. For example:> A <- matrix(1:12, ncol = 3) > B <- matrix(1:12, ncol = 3)> A[,1] [,2] [,3] [1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12> B[,1] [,2] [,3] [1,] 1 5 9 [2,] 2 6 10 [3,] 3 7 11 [4,] 4 8 12> A * B[,1] [,2] [,3] [1,] 1 25 81 [2,] 4 36 100 [3,] 9 49 121 [4,] 16 64 144 To then get cumulative column totals, you can do:> colSums(A * B)[1] 30 174 446 HTH, Marc Schwartz