向量和矩阵之间的自动乘法(Automatic multiplication between vector and matrix)

编程入门 行业动态 更新时间:2024-10-10 07:27:09
向量和矩阵之间的自动乘法(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 7

I 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.4

All 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 )

更多推荐

本文发布于:2023-08-03 07:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1386289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   乘法   矩阵   Automatic   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!