dreed75
dreed75

Reputation: 117

How do I efficiently multiply every 2 columns and sum the row

Maybe I should just go with a for loop but I want to see if there is a more efficient/faster way to do it.

I have a matrix of numbers, let's say 10x10. I want to multiply 1,1 by 1,2, then 1,3 times 1,4, etc and then sum those results for row 1. Then move to the next row and do the same thing. The end result would be a vector of 10.

It is possible for this matrix to be 1000x1000 so I want it to be as fast as possible. Thanks!

Upvotes: 1

Views: 111

Answers (1)

user3717023
user3717023

Reputation:

I would use

v = sum(M(:,1:2:end-1).*M(:,2:2:end),2);

Here M(:,1:2:end-1).*M(:,2:2:end) does multiplication: every element of an odd-numbered column of M is multiplied by its neighbor to the right. (This assumes even number of columns, otherwise the process you described is ill-defined.) Then every row is added up by the sum command.

On my computer, doing this for a 1000 by 1000 matrix takes 0.04 seconds.

Upvotes: 4

Related Questions