2

I have a problem with array manipulation in NumPy. If I create two arrays x and y, and do

x = x - y 

I get what I expect, that is each element of y is subtracted from the corresponding element of x, and thus x is modified. However, if I put this in a loop:

m = np.array([[1,2,3],[1,2,3]])
y = array([1, 1, 1])
for i in m:
    i = i - y

the matrix m remains unaltered. I am sure I am missing something very basic... How can I change the array m in a loop?

3 Answers 3

5

This is not related with numpy matrix, but how python deal with your

i = i - y

i - y produces a new reference of an array. When you assigns it to name i, so i is not referred to the one it was before, but the newly created array.

The following code will meet your purpose

for idx, i in enumerate(m):
    m[idx] = i - y
Sign up to request clarification or add additional context in comments.

Comments

3

Update: I realize that the easiest thing is to do

m = m-y

This does directly what I expected!

Comments

0

If working with an example where you are unable to avoid looping through the array but still want to change the row, do this

m = np.array([[1,2,3],[1,2,3]])
y = array([1, 1, 1])
for i in m:
    i -= y

Comments

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.