MATLAB: Multiplying a 1xM vector by a KxN matrix

MATLABmatrix

Hello there,
I have a 1xM vector, say V=[1 -1]; I would like to multiply it by a KxN matrix, say S=[0 0 1 1;1 1 0 0;1 0 1 0;0 1 0 1] such that at the beginning the first element of V gets multiplied by the first columns of S, then the second element of V be multiplied by the first columns of S, then the first element of V gets multiplied by the second column of of S, followed by the multiplication of the second element of V by the second column of S, and so forth. That is for the example mentioned above I get: [0 0 0 0 1 -1 1 -1;1 -1 1 -1 0 0 0 0;1 -1 0 0 1 -1 0 0;0 0 1 -1 0 01 -1]. I would appreciate if somebody can help me please. Thank you!

Best Answer

Use bsxfun, reshape, and permute:
>> V = [1,-1]
V =
1 -1
>> S = [0,0,1,1; 1,1,0,0; 1,0,1,0; 0,1,0,1]
S =
0 0 1 1
1 1 0 0
1 0 1 0
0 1 0 1
>> X = bsxfun(@times,S,reshape(V,1,1,[]));
>> reshape(permute(X,[3,2,1]),[],size(S,1)).'
ans =
0 0 0 0 1 -1 1 -1
1 -1 1 -1 0 0 0 0
1 -1 0 0 1 -1 0 0
0 0 1 -1 0 0 1 -1