Objective: Normalise a matrix such that all rows and columns sum to 1.
The below normalises each column, then row and repeats until row and column totals, equal one another.
This seems to work for randomly generated arrays.
However, the data I wish to use it on has some zeros – and that is generating lots of NaN and Infs, which is making things quite messy and sometimes when running the while loop won't execute (no error message, it just hops over it)
I've tried changing the while condition to be rounded to 3 decimal places (because that's good enough) but still no success.
a = rand(7)rows = sum(a,2) % orginal row totals
cols = sum(a,1) % original col totals
b = a;i = 1; % for counting how many iterations
while sum(b,1,"omitnan") ~= sum(b,2,"omitnan")' %when column totals == row totals, stop.
b = b ./ sum(b,1,"omitnan"); %divide by col totals
b = b ./ sum(b,2,"omitnan"); %divide by row totals
i = i + 1;endi %how many loops
b % normalised output
brows = sum(b,2,"omitnan") %check that all rows sum 1
bcols = sum(b,1,"omitnan") %check that all cols sum 1.
attached are two 7 x 7 matrices. These are the desired input for a.
Suggestions welcome.
edit:
The margfit function (row 345 – 376) in link below, is (I think) what I am trying to implement. My python is non-existant
Best Answer