2
votes

Given a matrix and a vector

A = [ 1 2; 2 4 ];
v = [ 2 4 ];

how can I divide each column of the matrix by the respective element of the vector? The following matrix should be

[ 1/2 2/4; 2/2 4/4 ]

Basically I want to apply a column-wise operation, with operands for each column stored in a separate vector.

2

2 Answers

4
votes

You should use a combination of rdivide and bsxfun:

A = [ 1 2; 2 4 ];
v = [ 2 4 ];
B = bsxfun(@rdivide, A, v);

rdivide takes care of the per element division, while bsxfun makes sure that the dimensions add up. You can achieve the same result by something like

B = A ./ repmat(v, size(A,1), 1)

however, using repmat results in an increased memory usage, which is why the bsxfun solution is preferable.

2
votes

Use bsxfun with the right divide (rdivide) operator and take advantage of broadcasting:

>> A = [ 1 2; 2 4 ];
>> v = [ 2 4 ];
>> out = bsxfun(@rdivide, A, v)

out =

    0.5000    0.5000
    1.0000    1.0000

The beauty with bsxfun is that in this case, the values of v will be replicated for as many rows as there are in A, and it will perform an element wise division with this temporary replicated matrix with the values in A.