[R] Matrix multiplication by multple constants
David Winsemius
dwinsemius at comcast.net
Fri Apr 20 16:35:38 CEST 2012
On Apr 20, 2012, at 4:57 AM, Dimitris Rizopoulos wrote:
> try this:
>
> x <- 1:3
> y <- matrix(1:12, ncol = 3, nrow = 4)
>
> y * rep(x, each = nrow(y))
Another way with a function specifically designed for that purpose:
sweep(y, 2, x, "*")
--
David.
>
>
> 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/
>
> ______________________________________________
> 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list