简体   繁体   English

是否可以在R中以以下方式将两个向量或矩阵与向量相乘?

[英]is it possible to multiply two vectors or matrix with vector in the following way in R?

A = 1:5
B = 11:15

I know A %*% B would give, AB = [205] ie 1*11+2*12+3*13+4*14+5*15 =205 我知道A %*% B会给, AB = [205] ie 1*11+2*12+3*13+4*14+5*15 =205
However, I want AB to be (without going through a loop, if possible) = (1*11)^2+(2*12)^2+(3*13)^2+(4*14)+(5*15)^2=10979 但是,我希望AB为(如果可能不进行循环) = (1*11)^2+(2*12)^2+(3*13)^2+(4*14)+(5*15)^2=10979

Follow-up: this solves the above problem sum((A*B)^2) as suggested by @Dason and @nicola. 后续:这解决了@Dason和@nicola提出的上述问题sum((A*B)^2)

Now what needs to be done in case A is a matrix ie A =matrix(1:10,2,5) After playing around I found this works: rowSums((A %*% diag(B))^2) 现在,如果情况A是矩阵, A =matrix(1:10,2,5)要做的事情就是A =matrix(1:10,2,5)玩了之后,我发现这行得通: rowSums((A %*% diag(B))^2)

尽管没有直接执行操作符/功能的操作,但将一些操作链接到一起很容易,而无需循环就可以得到所需的内容。

sum((A*B)^2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM