0

I am a novice programmer.

I would like to create a "subtraction matrix." (I lack the vocabulary to describe it). I would like to create a matrix from all the combination of subtractions.

v = [1, 5, 10]

0   4   9
4   0   5
9   5   0

I think I am missing something very basic with numpy but I do know what it is.

Thank you

3 Answers 3

2

You can use the outer method of the subtract ufunc. outer applies the operation (in this case subtraction) to every possible pair and arranges the result in a matrix:

v = [1, 5, 10]
np.absolute(np.subtract.outer(v, v))
# array([[0, 4, 9],
#        [4, 0, 5],
#        [9, 5, 0]])

Conveniently, it accepts lists etc. without you having to explicitly cast them to array.

Sign up to request clarification or add additional context in comments.

Comments

1

You can utilize numpy broadcasting:

v = np.array([1, 5, 10])

# v[:, None] creates a 2d array, when subtracted by a 1d array, the broadcasting rule will
# make a cartesian subtraction 
np.abs(v[:, None] - v)

#array([[0, 4, 9],
#       [4, 0, 5],
#       [9, 5, 0]])

1 Comment

Thanks a bunch you guys!
0

If you don't want to use numpy, you could use nested for loops:

v = [1, 5, 10]
vLen = len(v)
subMatrix = [[0]*vLen for x in range(vLen)] //creates empty matrix
for i in range(vLen):
    for j in range(vLen):
        subMatrix[j][i] = abs(v[i] - v[j])
# [[0, 4, 9],
#  [4, 0, 5],
#  [9, 5, 0]]

Edit: @aryamccarthy pointed out that for loops are less efficient than numpy broadcasting. Another alternative that he gave would be to use list comprehension for the same result:

v = [1, 5, 10]
subMatrix = [[abs(i - j) for i in v] for j in v]

6 Comments

By comparison to numpy broadcasting, this is terribly inefficient. Python's for-loops are super slow. Further, the asker only shows non-negative values in the intended output.
Good point, @aryamccarthy. I updated my answer to mention this and to only return positive values. I just wanted to show another perspective that shows how the task could be accomplished without third party packages.
Have you thought of expressing this as a list comprehension? [[abs(i - j) for i in v] for j in v]
Once again, you're right. That works much better. Maybe I should leave the answering to the pros until I get more python experience.
No, you're making positive contributions. This is how you learn, too—not just the asker. SO is a community; this answer was crafted by a community and started with you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.