Matrix multiplication and addition in R

Viewed 52

Perhaps I am not using the right terms in my search, but I was wondering if anyone could point out an easy way of doing the following:

I have two matrices:

mat1 = matrix(1:12, 3)
mat2 = matrix(c(1, 2, 1, 2, 3, 2, 1, 2), 2, 4)

I want to multiply each of row in a certain column of mat1 by the first row of mat2. For example, column 3 of mat1 would become (7*3, 8*3, 9*3)=(21, 24, 27). After this, I want to add the second row of mat2 to each row in a certain column of mat1, so the column 3 would become (21+2, 24+2, 27+2) = (23, 26, 29).

1 Answers

You can try the code below

t(t(mat1)*mat2[1,]+mat2[2,])

such that

> t(t(mat1)*mat2[1,]+mat2[2,])
     [,1] [,2] [,3] [,4]
[1,]    3    6   23   12
[2,]    4    7   26   13
[3,]    5    8   29   14
Related