I have two vectors:
x = c(1,2,3)
y = c(4,5,2)
and I want to multiply each element of x
with each element in y
and then sum it all up. So what I want to do is something along the lines of:
1*(4 + 5 + 2) + 2*(4 + 5 + 2) + 3*(4 + 5 + 2) = 11 + 22 + 33 = 66
Is there a way to do it without loops? Thanks in advance
Vectors can be multiplied in two different ways i.e., dot product and cross product. The results in both of these multiplications of vectors are different. Scalar multiplication of vectors or dot product gives a scalar quantity as a result whereas vector multiplication of vectors or cross product gives vector quantity.
When a vector is multiplied by a scalar quantity, then the magnitude of the vector changes in accordance with the magnitude of the scalar but the direction of the vector remains unchanged.
You made 2 rows, which can't be multiplied together. The general form of matrix multiplication is "Row-Dot-Column", which means take the dot product of each row with each column.
Here's what I'd use!
sum(x) * sum(y)
# [1] 66
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With