[R] A matrix multiplication

Jeffrey Robert Spies jspies at nd.edu
Thu Sep 27 18:34:46 CEST 2007


How about this:

a <- matrix(cbind(rep(2, 500), rep(3, 500)), 500, 2)
b <- matrix(cbind(rep(5, 500), rep(6, 500), rep(7, 500)), 500, 3)

matrix(apply(a, c(2), "*", b), nrow=500, ncol=6)

We apply the multiplier (quoted as specified in the apply help) with  
argument b to every column of a as specified by c(2), then reformat  
the results into a 500x6 matrix as desired.

Hope this helps,

Jeff.

On Sep 27, 2007, at 1:08 PM, Jose Luis Aznarte M. wrote:

> Dear all,
>     I'm having trouble using the 'apply' function to multiply some
> arrays. Let A be a 500x2 array and B a 500x3 array. I need a vector C
> which has 6 columns being the first three the result of A[,1] * B and
> the second three the result of A[,2] * B. What is the most  
> efficient way
> to express that? I'm trying to use 'apply' with no success...
>     Thanks for your help!
>
>
> --                                                      --
> Jose Luis Aznarte M.       http://decsai.ugr.es/~jlaznarte
> Department of Computer Science and Artificial Intelligence
> Universidad de Granada           Tel. +34 - 958 - 24 04 67
> GRANADA (Spain)                  Fax: +34 - 958 - 24 00 79
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting- 
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list