0

From Creating a matrix of arbitrary size where rows sum to 1?, we can simply normalize the values by dividing each value in the matrix by the sum of all values to make sure that it sums to 1.

For example:

cols, rows = 5, 5
matrix = np.random.rand(rows, cols)
matrix/matrix.sum(axis=1)[:,None]

How to create a matrix of arbitrary size where rows sum to 0?

I've tried:

cols, rows = 5, 5
x = np.random.rand(rows, cols)
z = x - sum(sum(x)) / (rows*cols)

It goes to a number close to zero but never summing zero =(

alvas
  • 115,346
  • 109
  • 446
  • 738
  • I think you will never get exactly 0 due to numerical rounding errors if you're using float. One solution would be to use integers. Is there a reason you need it to be exactly 0 instead of numerically 0? – overfull hbox Dec 27 '18 at 14:56
  • Also, in your top example, each row sums to 1 rather than the whole matrix summing to 1. – overfull hbox Dec 27 '18 at 15:00

1 Answers1

1

You are subtracting the average value of x from itself to create z, which will give you a matrix that sums to 0. To get the rows to sum to zero you have to subtract the average value of a row from each element in that row.

cols, rows = 5, 5
x = np.random.rand(rows, cols)
z = (x - np.average(x,axis=0)).T

This code finds the average of the columns and subtracts them as when subtracting a 1D array from a 2D array the 1D array will be subtracted from each row. This gives a matrix whose columns sum to zero, and so transposing gives a matrix whose rows sum to zero.

As Tyler Chen mentioned you won't get exactly 0 due to rounding error, but this will get you close.

I hope that helps!

Erik Parkinson
  • 356
  • 2
  • 9