1

I have a vector row b = [b1 b2 b3 b4] and a Matrix M = [m1 m2 m3 m4] where the m1,m2,m3 and m4 are column vectors of size N.

I want to do perform a multiplication so that I can have the following result in Matlab: Result = [b1*m1 b2*m2 b3*m3 b4*m4]

and also, what if B = [b11 b12 b13; b21 b22 b23;b31 b32 b33 b34;b41 b42 b43 b44] How would I get:

Result2 = [b11*m1 + b12*m2 + b13*m2;
           b21*m1 + b22*m2 + b23*m2;
           b31*m1 + b32*m2 + b33*m2;
           b41*m1 + b42*m2 + b43*m2]

Thank you in advance.

bremen_matt
  • 6,902
  • 7
  • 42
  • 90
kirikoumath
  • 723
  • 9
  • 20

3 Answers3

3

If I understand you correctly:

bsxfun(@times,m,b)
bla
  • 25,846
  • 10
  • 70
  • 101
  • I think OP is looking for this and perfect for `bsxfun`. +1 – Divakar May 27 '14 at 18:53
  • thanks Divkar, I guess the bsxfun will be a bit faster than matrix multiplication and diag... – bla May 27 '14 at 18:55
  • yeah I mean the first problem seems like tailor-made for `bsxfun`, but still would be nice to some benchmarks if any working alternative solution is provided. – Divakar May 27 '14 at 19:06
2

For the first problem, I think natan's answer fits there perfectly.

For the second problem -

t1 = bsxfun(@times,[M(:,1) M(:,2) M(:,2)],permute(B,[3 2 1]))
Result2 = sum(reshape(permute(t1,[1 3 2]),size(t1,1)*size(t1,3),[]),2)

If you need the final result to be in Nx4 size, use this - reshape(Result2,[],4).

Note: One very similar question that might be interesting to you - bsxfun implementation in matrix multiplication

Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • @user5503 Sorry I must have put the `sum` there. Edited! You expect `Result2` to be of `(4*N)x1` right? – Divakar May 27 '14 at 19:12
  • Thank you. What if I wanted the result to be N by 4 matrix? – kirikoumath May 27 '14 at 19:15
  • @user5503 `reshape(Result2,[],4)` – Divakar May 27 '14 at 19:16
  • @user5503 You are welcome and glad it worked for you! – Divakar May 27 '14 at 19:30
  • @user5503 Let me suggest you to look into this question as it is very close to your question - http://stackoverflow.com/questions/23807960/bsxfun-implementation-in-matrix-multiplication All these info are edited into the solution for future reference. – Divakar May 27 '14 at 19:32
1

You can use the diag function to create a diagonal matrix that you can use to post-multiply your matrix:

M*diag(b)
eigenjohnson
  • 208
  • 1
  • 9