How do I divide matrix elements by column sums in MATLAB?

Solution 1:

Here's a list of the different ways to do this ...

  • ... using bsxfun:

    B = bsxfun(@rdivide,A,sum(A));
    
  • ... using repmat:

    B = A./repmat(sum(A),size(A,1),1);
    
  • ... using an outer product (as suggested by Amro):

    B = A./(ones(size(A,1),1)*sum(A));
    
  • ... and using a for loop (as suggested by mtrw):

    B = A;
    columnSums = sum(B);
    for i = 1:numel(columnSums)
      B(:,i) = B(:,i)./columnSums(i);
    end
    

Update:

As of MATLAB R2016b and later, most built-in binary functions (list can be found here) support implicit expansion, meaning they have the behavior of bsxfun by default. So, in the newest MATLAB versions, all you have to do is:

B = A./sum(A);

Solution 2:

a=[1 4;4 10]
a =
     1     4
     4    10

a*diag(1./sum(a,1))
ans =
    0.2000    0.2857
    0.8000    0.7143