3

Let v be a row vector (1 x n matrix) and M be a n x m matrix. I use the following piece of code to create a "weighted vector" (I hope the comments explain what it's supposed to be doing):

weighted_M = bsxfun(@times,v',M);
%creates a matrix with the i-th row of M being weighted (multiplied) by the i-th element of v
weighted_v = sum(weighted_M);
%sums the columns of weighted_M

Now the actual question: I have to do the same calculation for a lot of input vectors v. So instead I would like to input a matrix V that contains the vectors v as rows and output a matrix that contains the weighted vectors as rows. Is there any way to do this without using for loops?

NumRok
  • 33
  • 3

1 Answers1

5

If V is of size [k,n] and M is of size [n,m], and you're looking for the k weighted vectors, then you might simply need

weighted_vs = V*M;

an element of which is equal to

weighted_vs_ij = (V*M)ij = sum_l V_il * M_lj

First you multiply each row of M with a corresponding element of V (V_il * M_lj above for a fix i), then sum up as a function of the first index.

The result are the k weighted row vectors, each of length m.

  • 1
    Very useful thank you! (also I'm feeling slightly stupid now not realizing that it's just ordinary matrix multiplication). Do you happen to know anything about the runtime of this operation? – NumRok Dec 06 '15 at 19:41
  • 2
    @NumRok only that [it's as fast as it gets](http://stackoverflow.com/questions/6058139/why-is-matlab-so-fast-in-matrix-multiplication):) If it's doable with matrix operations, use that. If it's not, use `bsxfun` if it's doable with that. If it's not, use a loop. – Andras Deak -- Слава Україні Dec 06 '15 at 19:47