Reputation: 317
This is my code:
a <-c(1,2,3)
b <-t(a)
print(a*b)
I would expect the result to be 14, since a column vector multiplied with a row vector with fitting dimensions should be a skalar.
However, I get:
print (a*t(a))
[,1] [,2] [,3]
[1,] 1 4 9
Hence the partial sums instead of the whole sum. How can I fix this?
Upvotes: 15
Views: 56694
Reputation: 153
You can simply do this,
> a <-c(1,2,3)
> b <-t(a)
> b %*% a
Here, %*%
acts as a matrix product.
Upvotes: 1
Reputation: 17
simply do this
a <-c(1,2,3)
> b<-t(a)
> b
> t(b)
then
sum(a*t(b)) [1] 14
Upvotes: 0
Reputation: 2651
If what you essentially want is the sum of the products, then all you need is sum(a*a)
Upvotes: 20
Reputation: 42629
Two problems, multiplication in the wrong order, and the wrong multiply function.
> print(t(a)%*%a)
[,1]
[1,] 14
Equivalently:
> a=matrix(c(1,2,3),ncol=3)
> print (a %*% t(a))
[,1]
[1,] 14
Here a
is a matrix of 1 row, three columns.
See ?"%*%"
and ?"*"
Upvotes: 22