Claire Claire - 5 months ago 23
Python Question

Iterating through matrices Python

If I have two lists and want to iterate through subtracting one from the other how would I go about this? I was thinking broadcasting. Right now I have:

array1 = [0,2,2,0]
array2 = [2,2,0,1]


I would like to subtract array1 from each value in array2 and make a new matrix of outputs:

output = [2, 0, 0, 2,
2, 0, 0, 2,
0, -2, -2, 0,
1, -1, -1, 1]


so in the end it's a 4x4 matrix.

Is this possible? Is the easiest way to use broadcasting? I was thinking of making each row value in array2 into it's own array, subtracting that from array2 using broadcasting, then summing all the array's at the end into one big array (using Numpy)... is there an easier way?

If I have two lists and want to iterate through subtracting one from the other how would I go about this? I was thinking broadcasting. Right now I have:

array1 = [0,2,2,0]
array2 = [2,2,0,1]


I would like to subtract array1 from each value in array2 and make a new matrix of outputs:

output = [2, 0, 0, 2,
2, 0, 0, 2,
0, -2, -2, 0,
1, -1, -1, 1]


so in the end it's a 4x4 matrix.

Is this possible? Is the easiest way to use broadcasting? I was thinking of making each row value in array2 into it's own array, subtracting that from array2 using broadcasting, then summing all the array's at the end into one big array (using Numpy)... is there an easier way?

Answer Source

Broadcasting with numpy:

>>> a1 = np.array([0,2,2,0])
>>> a2 = np.array([2,2,0,1])
>>> a2[:, np.newaxis] - a1
array([[ 2,  0,  0,  2],
       [ 2,  0,  0,  2],
       [ 0, -2, -2,  0],
       [ 1, -1, -1,  1]])