I have a matrix beta with nrow=10
and ncol=10
and a second matrix data with nrow=10
and ncol=10
. I want to multiply the columns from beta with the rows from data for ever element.
I already tried to write a for loop:
solution1 <- matrix(NA,10,10)
for(i in 1:nrow(data)){solution <- matrix(beta*data[i,])}
but this jut shows me a list of 10 times "NA"
I don't know what I am doing wrong. I actually expect a matrix with nrow=10
and ncol=10
. Maybe someone has an idea and can help?
The operation of multiplying each element of a row of a matrix with the corresponding element of a column of another matrix is the same as the matrix multiplication defined in linear algebra.
R has a matrix multiplication operator %*%
solution <- beta %*% data
After reading your clarification I found the following simple solution. Multiplying all values element-wise and then taking the transpose of the matrix.
solution <- t(beta*data)
Which outputs the following results
[,1] [,2] [,3]
[1,] 1 4 9
[2,] 16 25 36
[3,] 49 64 81
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.