[英]R: How can I fix my for-loop so it multiplies every element of a row with the corresponding element of a column?
I have a matrix beta with nrow=10
and ncol=10
and a second matrix data with nrow=10
and ncol=10
. 我有与基质的β nrow=10
和ncol=10
和具有第二矩阵数据nrow=10
和ncol=10
。 I want to multiply the columns from beta with the rows from data for ever element. 我想将beta中的列乘以ever元素中数据的行。
I already tried to write a for loop: 我已经尝试编写一个for循环:
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" 但是这个突出显示了10次“不适用”的列表
I don't know what I am doing wrong. 我不知道我在做什么错。 I actually expect a matrix with nrow=10
and ncol=10
. 其实,我期待着与矩阵nrow=10
和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 %*%
R具有矩阵乘法运算符%*%
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.