[R] Matrix multiplication by multple constants

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Fri Apr 20 10:57:17 CEST 2012


try this:

x  <- 1:3
y  <- matrix(1:12, ncol = 3, nrow = 4)

y * rep(x, each = nrow(y))


I hope it helps.

Best,
Dimitris


On 4/20/2012 10:51 AM, Vincy Pyne wrote:
> Dear R helpers
>
> Suppose
>
> x<- c(1:3)
>
> y<- matrix(1:12, ncol = 3, nrow = 4)
>
>> y
>       [,1] [,2] [,3]
> [1,]    1    5    9
> [2,]    2    6   10
> [3,]    3    7   11
> [4,]    4    8   12
>
> I wish to multiply 1st column of y by first element of x i.e. 1, 2nd column of y by 2nd element of x i.e. 2 an so on. Thus the resultant matrix should be like
>
>> z
>
>       [,1]   [,2]    [,3]
>
> [1,]    1    10    27
>
> [2,]    2    12    30
>
> [3,]    3    14    33
>
> [4,]    4    16    36
>
>
> When I tried simple multiplication like x*y, y is getting multiplied column-wise
>
>> x*z
>        [,1] [,2] [,3]
> [1,]    1    5    9
> [2,]    4   12   20
> [3,]    9   21   33
> [4,]   16   32   48
>
>
> Kindly guide
>
> Regards
>
> Vincy
>
> 	[[alternative HTML version deleted]]
>
>
>
>
> ______________________________________________
> 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.

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list