user1862770
user1862770

Reputation: 317

multiply two vectors - I want a scalar but I get a vector?

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

Answers (4)

Ankur Gautam
Ankur Gautam

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

Hal Hayden Stirrup
Hal Hayden Stirrup

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

A_K
A_K

Reputation: 2651

If what you essentially want is the sum of the products, then all you need is sum(a*a)

Upvotes: 20

Matthew Lundberg
Matthew Lundberg

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

Related Questions