Makiyo
Makiyo

Reputation: 451

Matrix dot-product in R

I am tring to figure out how to the dot product.

b = matrix(1:70, ncol=7)
g= matrix(1:48, ncol=6)
resulta = matrix(0,6,7)
for (c in 1:ncol(b)){
  for (i in 1:ncol(g)){
    resulta[i,c] <- sum((g[,i]) * (b[,c]))
  }
}

Warning messages:

1: In (g[, i]) * (b[, c]) :
  longer object length is not a multiple of shorter object length
2: In (g[, i]) * (b[, c]) :
  longer object length is not a multiple of shorter object length

...........................Total 42 alike messages

Upvotes: 1

Views: 4314

Answers (1)

Vash
Vash

Reputation: 1787

Whenever you multiply matrices, you have to make sure that dimensions are such that #columns of first matrix is same as #rows of second i.e. if first matrix is a x b, second matrix has to be b x c (c and a may or may not be equal) so that the resultant matrix is a x c.

In your case, matrix b is 70 x 7 meaning matrix g should be a 7 x something matrix. In other words, matrix g should have exactly 7 rows.

Once you have fixed the dimensions, try this for quick matrix multiplication:
resulta <- b %*% g
resulta

Upvotes: 5

Related Questions