向量和矩阵之间的自动乘法(Automatic multiplication between vector and matrix)
我有这个R代码:
> coef [1] 1.5 2.4 3.9 4.4 > y [,1] [,2] [,3] [,4] [1,] 1 2 12 45 [2,] 5 6 7 8 [3,] 9 10 2 12 [4,] 13 14 15 45 [5,] 17 18 39 7我必须将列的每个值与相应的系数相乘。 结果应该是:
First column: 1*1.5 5*1.5 9*1.5 13*1.5 17*1.5 Second column: 2*2.4 6*2.4 10*2.4 14*2.4 18*2.4 Third column: 12*3.9 7*3.9 2*3.9 15*3.9 39*3.9 Fourth column: 45*4.4 8*4.4 12*4.4 45*4.4 7*4.4所有列的值在矢量中的相同索引处由相同的系数模拟。
我怎样才能做这个计算?
解决方案可以是:
> y[,1] <- y[,1] * coef[1] > y[,2] <- y[,2] * coef[2] > y[,3] <- y[,3] * coef[3] > y[,4] <- y[,4] * coef[4]但似乎没有太优化! 更好的东西?
谢谢!
I have this R code:
> coef [1] 1.5 2.4 3.9 4.4 > y [,1] [,2] [,3] [,4] [1,] 1 2 12 45 [2,] 5 6 7 8 [3,] 9 10 2 12 [4,] 13 14 15 45 [5,] 17 18 39 7I have to multiply each value of the column with the respective coef. The result should be:
First column: 1*1.5 5*1.5 9*1.5 13*1.5 17*1.5 Second column: 2*2.4 6*2.4 10*2.4 14*2.4 18*2.4 Third column: 12*3.9 7*3.9 2*3.9 15*3.9 39*3.9 Fourth column: 45*4.4 8*4.4 12*4.4 45*4.4 7*4.4All the column's values moltiplied by the same coefficient at the same index in the vector.
How can I do this calculation?
The solution could be:
> y[,1] <- y[,1] * coef[1] > y[,2] <- y[,2] * coef[2] > y[,3] <- y[,3] * coef[3] > y[,4] <- y[,4] * coef[4]But doesn't seem too optimized! Something better?
Thank you!
最满意答案
这会给你你想要的东西:
t( t(y) * coef )This will give you what you want:
t( t(y) * coef )更多推荐
发布评论