I need to generate a matrix where the diagonal are zeroes and every column and row has a sum of zero.
For example first row 0, 4, -2, -1, 1 = sum is 0
or the first column 0, -4, 2, 1, 1 = sum is 0
This works for every column and row of course
0, 4, -2, -1, -1
-4, 0, 3, 3, -2
2, -3, 0, -1, 2
1, -3, 1, 0, 1
1, 2, -2, -1, 0
The diagonal is always filled with zeroes. Im trying to create a weighted graph that is balanced for every connection it does.
EDIT: I have also forgotten that the matrix is mirrored through the diagonal with * (-1)
For 1×1, 2×2 and 3×3 matrices, the only matrices that work are the following (where r is any random number):
With 4×4 matrices, you can start with a zero matrix and add randomness by repeatedly performing an operation that doesn't affect the zero-sum property. Choose any four cells at the corners of a quadrilateral (as long as they aren't on the the main diagonal). Treating the corners of this quadrilateral as a 2×2 matrix, you can add any multiple of the following matrix without affecting the row and column sums:
For example, a zero 5×5 matrix can be transformed into the following in four steps:
Here's some Python code that implements this algorithm:
Sample output: