[R] columnwise multiplication?
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Fri Jun 23 18:10:13 CEST 2006
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
More information about the R-help
mailing list