Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Is there an easy way to divide each matrix element by the column sum? For example:

input:

1  4

4  10

output:

1/5  4/14

4/5  10/14
like image 452
danatel Avatar asked Nov 20 '09 20:11

danatel


People also ask

How do I sum each column of a matrix in MATLAB?

Description. S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.

How do you divide a matrix in MATLAB?

Description. x = A ./ B divides each element of A by the corresponding element of B . The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

How do you split a matrix by an element in MATLAB?

X = A ./ B performs right-array division by dividing each element of A by the corresponding element of B . X = rdivide( A , B ) is an alternative way to execute X = A./B .

How do you divide a matrix by a vector?

A matrix is a 2D array, while a vector is just a 1D array. If we want to divide the elements of a matrix by the vector elements in each row, we have to add a new dimension to the vector. We can add a new dimension to the vector with the array slicing method in Python.


2 Answers

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);
like image 52
gnovice Avatar answered Sep 20 '22 06:09

gnovice


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
like image 1
user3246465 Avatar answered Sep 22 '22 06:09

user3246465