Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I divide columns of a matrix by elements of a vector, element-wise?

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.

like image 803
Jakub Arnold Avatar asked Dec 13 '25 23:12

Jakub Arnold


2 Answers

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.

like image 128
jdoerrie Avatar answered Dec 16 '25 05:12

jdoerrie


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.

like image 28
rayryeng Avatar answered Dec 16 '25 07:12

rayryeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!