kirikoumath
kirikoumath

Reputation: 733

Vector times Matrix - Two cases

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.

Upvotes: 1

Views: 173

Answers (3)

eigenjohnson
eigenjohnson

Reputation: 208

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

M*diag(b)

Upvotes: 1

Divakar
Divakar

Reputation: 221684

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

Upvotes: 2

bla
bla

Reputation: 26069

If I understand you correctly:

bsxfun(@times,m,b)

Upvotes: 3

Related Questions