robguinness
robguinness

Reputation: 16656

How to perform this kind of matrix division in Matlab?

This problem is probably less to do with Matlab and more to do with matrix algebra (which I mostly forget from my college courses). Say I have a m x n matrix X and a m x 1 matrix B. How would I divide the X by B such that all the elements of the ith row of X are piecewise divided by the ith row of B, resulting in another m x n matrix Y?

E.g.

X = [2 4 8; 3 9 27; 4 16 64]
B = [2; 3; 4]

X ? B = [2/2 4/2 8/2; 3/3 9/3 27/3; 4/4 16/4 64/4]
ans   = 
           1     2     4
           1     3     9
           1     4    16

Upvotes: 2

Views: 577

Answers (4)

veeresh
veeresh

Reputation: 69

X = [2 4 8; 3 9 27; 4 16 64]

B = [2; 3; 4]

Result= X./B(:,ones(1,3)) %is faster then repmat

Result =

 1     2     4
 1     3     9
 1     4    16

Upvotes: 0

Ramsharan
Ramsharan

Reputation: 2064

X is m x n and B is m x 1

size(X,2) gives the value of n i.e. number of columns

So, you need to do:

X./repmat(B,1,size(X,2))

Upvotes: 0

angainor
angainor

Reputation: 11810

Better not use repmat - it is slow and allocates additional memory for the workspace. You can use bsxfun, which is an inbuilt function, so it is faster and avoids the extra workspace:

X = [2 4 8; 3 9 27; 4 16 64]
B = [2; 3; 4]
bsxfun(@rdivide, X, B)

ans =

 1     2     4
 1     3     9
 1     4    16

Upvotes: 11

robguinness
robguinness

Reputation: 16656

Junuxx's comment pointed me in the right direction. The solution I used to get what I wanted is:

B_prime = repmat(B,1,3)

X ./ B_prime

ans =

 1     2     4
 1     3     9
 1     4    16

I'd still like to know what this kind of operation is called (if it even has a formal name).

Upvotes: 1

Related Questions