alvas
alvas

Reputation: 122260

Creating a matrix of arbitrary size where rows sum to 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 =(

Upvotes: 0

Views: 700

Answers (1)

Erik Parkinson
Erik Parkinson

Reputation: 356

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!

Upvotes: 1

Related Questions