Finding dot product in r

Jonathan O'Farrell picture Jonathan O'Farrell · Feb 3, 2015 · Viewed 31k times · Source

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!

Answer

Craig picture Craig · Sep 4, 2015

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