Divide each column by the sum of the column in a matrix

I am sure this is an elementary question, but I could not find the answer when searching the Matlab website. I was wondering how to divide each column in a matrix by the sum of that column and do the same process for all the columns in a matrix. The result should then be returned as a new matrix.
As an example take the following matrix
D = [-0.442898926677253 -0.165258150390309 0.850111606631490 -0.801783725737275;
-0.505610279127129 0.455832504673115 -0.205467096352270 4.76435784320108e-15;
-0.540885414880185 -0.746406858955920 -0.439177413926944 0.534522483824847;
-0.505610279127129 0.455832504673115 -0.205467096352275 0.267261241912423];
Now, for the first column;
U(:,1)/sum(U(:,1))
gets the first column of D divided by the sum of the column, but how do I do this for all of the columns and return the output as a new matrix?

2 Comments

U(:,1)/sum(U(:,1)) gets the first column of D divided by the sum of the column
No, it does that for U, not D.
Yes, well observed I should have written D in the expression.

Sign in to comment.

 Accepted Answer

D./sum(D)

6 Comments

Exactly. To be safe specify the dimension to sum over:
D ./ sum(D, 1)
Then providing a row vector does not sum over the wrong direction.
Thanks, this solves my problems for numeric computattions. I tried using this with the symbolic toolbox and I end up with some infinity entries and . Is it because when I use an unkown parameter (for example 'd') then the magnitude is uknown since the parameter is unknown and I cannot use the sum() function behaves weirdly?
Or you have columns that sum to 0.
@Torsten yes, If the columns sum to 0 then the parameter must cancel each other out and infinity is returned. I also get NaN returned for some entries. Wonder what could cause it to return as 'not a number'?
Just display D and look at the respective columns. You should be able to find the reason by inspection.
Wonder what could cause it to return as 'not a number'?
That would happen if the column sum is zero, and the column also contains some zeros, e.g.,
D=[-1;0;1];
D/sum(D)
ans = 3×1
-Inf NaN Inf

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2021b

Asked:

on 19 May 2022

Edited:

on 20 May 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!