Skip to content Skip to sidebar Skip to footer

Semantics Of Generating Symmetric Matrices In Numpy

I tried to make a random symmetric matrix to test my program. I don't care about the data at all as long as it is symmetric (sufficient randomness is no concern at all). My first

Solution 1:

Those statements aren't semantically equivalent. x.T returns a view of the original array. in the += case, you're actually changing the values of x as you iterate over it (which changes the values of x.T).

Think of it this way ... When your algorithm gets to index (3,4), it looks something like this in pseudocode:

x[3,4] = x[3,4] + x[4,3]

now, when your iteration gets to (4,3), you do

x[4,3] = x[4,3] + x[3,4]

but, x[3,4] is not what it was when you started iterating.


In the second case, you actually create a new (empty) array and change the elements in the empty array (never writing to x). So the pseudocode looks something like:

y[3,4] = x[3,4] + x[4,3]

and

y[4,3] = x[4,3] + x[3,4]

which obviously will give you a symmetric matrix (y.

Post a Comment for "Semantics Of Generating Symmetric Matrices In Numpy"