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
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.
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.
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 .
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With