Jim Maas
Jim Maas

Reputation: 1729

Can I multiply vectors of different lengths?

v1 <- c(1,2)
v2 <- c(3,4,5,6)

Is there a way to multiply these two vectors such that the result is a vector dim(1,3)
such as (11,14,17)

This is analogous to all possible dim(1,2) multiplication combinations such as (1,2) %x% t(3,4), (1,2) %x% t(4,5), (1,2) %x% t(5,6)

It seems so simple, have looked and no luck.

Upvotes: 1

Views: 4134

Answers (4)

Matthew Plourde
Matthew Plourde

Reputation: 44614

Another option:

na.omit(filter(v2, rev(v1)))

You could also use embed:

apply(embed(v2, 2), 1, FUN='%*%', rev(v1))

Upvotes: 1

Carl Witthoft
Carl Witthoft

Reputation: 21492

Similar to James' answer, but maybe simpler:

sapply(1:(length(v2)-1), function(j) sum(v1*v2[j:j+1]))

Since you're only multiplying vectors (aka 1-by-N matrices :-) ), there's no need to dive into the matrix ops.

Upvotes: 1

Spacedman
Spacedman

Reputation: 94162

Create a 2-row matrix:

> rbind(v2[-length(v2)],v2[-1])
     [,1] [,2] [,3]
[1,]    3    4    5
[2,]    4    5    6

Then it's just matrix multi:

> v1 %*% rbind(v2[-length(v2)],v2[-1])
     [,1] [,2] [,3]
[1,]   11   14   17

and subset if you want a vector:

> (v1 %*% rbind(v2[-length(v2)],v2[-1]))[1,]
[1] 11 14 17

Upvotes: 7

James
James

Reputation: 66834

Use subsetting and cbind to create a matrix of your combinations, then apply across the rows of this with your multiplication.

apply(cbind(v2[-length(v2)],v2[-1]),1,function(x) v1%*%x)
[1] 11 14 17

Upvotes: 3

Related Questions