Reputation: 3324
I want to multiply every column of a M × N matrix by corresponding element of a vector of size N.
I know it's possible using a for loop. But I'm seeking a more simple way of doing it.
Upvotes: 1
Views: 503
Reputation: 9075
I think this is what you want:
mat1=randi(10,[4 5]);
vec1=randi(10,[1 5]);
result=mat1.*repmat(vec1,[size(mat1,1),1]);
rempat
will replicate vec1
along the rows of mat1
. Then we can do element-wise multiplication (.*)
to "multiply every column of a M × N
matrix by corresponding element of a vector of size N
".
Edit: Just to add to the computational aspect. There is an alternative to repmat
that I would like you to know. Matrix indexing can achieve the same behavior as repmat
and be faster. I have adopted this technique from here.
Observe that you can write the following statement
repmat(vec1,[size(mat1,1),1]);
as
vec1([1:size(vec1,1)]'*ones(1,size(mat1,1)),:);
If you see closely, the expression boils down to vec1([1]'*[1 1 1 1]),:);
which is again:
vec1([1 1 1 1]),:);
thereby achieving the same behavior as repmat
and be faster. I ran three solutions 100000
times, namely,
repmat
: 0.824518 secondsbsxfun
provided by @LuisMendo : 0.683331 secondsYou can observe that bsxfun
is slightly faster.
Upvotes: 4
Reputation: 112659
Although you can do it with repmat
(as in @Parag's answer), it's often more efficient to use bsxfun
. It also has the advantage that the code (last line) is the same for a row and for a column vector.
%// Example data
M = 4;
N = 5;
matrix = rand(M,N);
vector = rand(1,N); %// or size M,1
%// Computation
result = bsxfun(@times, matrix, vector); %// bsxfun does an "implicit" repmat
Upvotes: 3