Mehraban
Mehraban

Reputation: 3324

Simple way to multiply column elements by corresponding vector elements in MATLAB?

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

Answers (2)

Autonomous
Autonomous

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,

  1. Solution using repmat : 0.824518 seconds
  2. Solution using indexing technique explained above : 0.734435 seconds
  3. Solution using bsxfun provided by @LuisMendo : 0.683331 seconds

You can observe that bsxfun is slightly faster.

Upvotes: 4

Luis Mendo
Luis Mendo

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

Related Questions