Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply vectors without a loop?

Tags:

r

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

like image 243
broccoli Avatar asked Oct 16 '12 22:10

broccoli


People also ask

What are the two ways to multiply vectors?

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.

Can you multiply a vector by a constant?

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.

Can two row vectors be multiplied?

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.


1 Answers

Here's what I'd use!

sum(x) * sum(y)
# [1] 66
like image 121
Josh O'Brien Avatar answered Oct 05 '22 12:10

Josh O'Brien