[R] Column wise matrix multiplication

(Ted Harding) Ted.Harding at wlandres.net
Mon Feb 20 18:54:17 CET 2012


On 20-Feb-2012 Graziano Mirata wrote:
> Hi all,
> I am trying to multiply each column of a matrix such to have
> a unique resulting vector with length equal to the number of
> rows of the original matrix. In short I would like to do what
> prod(.) function in Matlab does, i.e.
> 
> A <-matrix(c(1:10),5,2)
> 
> V = A[,1]*A[,2]
> 
> Thank you
> 
> Graziano

The Matlab prod(A,2) function computes the products along the
rows of the matrix A and returns the result as a column vector,
of length equal to the number of rows in A, which seems to be
what you describe.

Your code above does this for your 2-column example, but the
result is a simple "R vector" which is not an array (and in
particular is not a column vector):

  A[,1]*A[,2]
  # [1]  6 14 24 36 50

  dim(A[,1]*A[,2])
  # NULL

For a matrix A with arbitrary number of columns, if you wanted
the row sums rather than the row products, you could use the
R function rowSums():

  rowSums(A)
  # [1]  7  9 11 13 15

This is still a dimensionless "simple R vector":

  dim(rowSums(A))
  # NULL

Unfortunately, there seems to be no equivalent for products
(e.g. "rowProds"). But you can define one:

  rowProds <- function(X){ apply(X,1,FUN="prod") }

  rowProds(A)
  # [1]  6 14 24 36 50

Even then, the result is a "simple R vector", without dimensions:

  dim(rowProds(A))
  # NULL

If you need an array (row) vector then you can apply t():

  t(rowProds(A))
  #      [,1] [,2] [,3] [,4] [,5]
  # [1,]    6   14   24   36   50

or t(t()) for a column vector:

  t(t(rowProds(A)))
  #      [,1]
  # [1,]    6
  # [2,]   14
  # [3,]   24
  # [4,]   36
  # [5,]   50

Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 20-Feb-2012  Time: 17:54:13
This message was sent by XFMail



More information about the R-help mailing list