Finding Dot Product in R

Finding Dot Product in R

I am trying to find the dot product of two matrices in R. In the q matrix, which must be transposed, I have three different q values that I randomly generated earlier, and in the z matrix three randomly generated z values that serve as coordinates of a random point i. I have:

    z0= NULL
    for (i in 1:100){
        z0[i]= 1
    }
    z1= runif(100, min=0, max= 20)
    z2= runif(100, min=0, max=20)
    q0= runif(1, 0, 1)
    q1= runif(1, 0, 1)
    q2= runif(1, 0, 1)
    i= runif(1, 1, 101)
    i= ceiling(i-1)
    q= matrix(c(q0,q1,q2), ncol=3)
    z= matrix(c(z0[i],z1[i],z2[i]), ncol=3)
    s[i]= t(q)*z

However, when I try to calculate s[i], I get Error in t(q) * z : non-conformable arrays. I am not sure why this would be as I they seem to both have the same length.

This is my first time using R so I am not really sure what is going on.

Thanks!

17

4 Answers

Without using matrices or any special libraries:

The dot product of two vectors can be calulated by multiplying them element-wise with * then summing the result.

a <- c(1,2,3)
b <- c(4,5,6)

sum(a*b)
1

As Pascal says, dot product in R is %*%. I am able to use this successfully on your sample data:

> z0= NULL
> for (i in 1:100){
+     z0[i]= 1
+ }
> z1= runif(100, min=0, max= 20)
> z2= runif(100, min=0, max=20)
> q0= runif(1, 0, 1)
> q1= runif(1, 0, 1)
> q2= runif(1, 0, 1)
> i= runif(1, 1, 101)
> i= ceiling(i-1)
> q= matrix(c(q0,q1,q2), ncol=3)
> z= matrix(c(z0[i],z1[i],z2[i]), ncol=3)
> t(q)%*%z
          [,1]     [,2]     [,3]
[1,] 0.3597998 3.227388 2.960053
[2,] 0.3544622 3.179510 2.916141
[3,] 0.3550781 3.185035 2.921208
> z%*%t(q)
         [,1]
[1,] 4.340265

Sample Answer:

library(geometry)
dot(A,B)

Since it seems like others have tackled your issue, I'll just add on to say that if you want a special dot product function, you can write one yourself:

dot <- function(x, y){   # x and y can be vectors or matrices
    result <- t(x)%*%y   # %*% is the matrix multiplication operator
    print(result)        # t(x) denotes the transpose of x
}

Or, as @user3503711 says in his answer, you can just use the dot() function from the geometry library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.