Claire - 1 year ago 43
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?

Broadcasting with `numpy`:
``````>>> a1 = np.array([0,2,2,0])