OnurA
OnurA

Reputation: 651

How to copy content of a numpy matrix to another?

I have a simple question about basics of python and numpy module. I have a function as following:

def update_x_last(self, x):
    self.x_last = x

The class attribute x_last and function argument x are both initialized as of type numpy.matrix and of the same shape. (x.shape = x_last.shape = (4,1)

I have noticed that the code above does not copy the content of the argument x to x_last, but it makes the object x_last point to the address of x.

However what I want to do is the following:

What is the best way to do this?

Edit: the requirement 'Don't change the address of 'self.x_last' was unimportant for me. The only required behaviour is the second requirement to copy only the content.

Upvotes: 0

Views: 199

Answers (2)

Eric
Eric

Reputation: 97601

If the shapes are the same, then any of these meet both of your requirements:

self.x_last[...] = x
# or self.x_last[()] = x
# or self.x_last[:] = x

I'd argue that the first one is probably most clear


Let's take a look at your requirements quickly:

Copy only the content of x to self.x_last

Seems reasonable. This means if that if x continues to change, then x_last won't change with it

Don't change the address of self.x_last

This doesn't buy you anything. IMO, this is actively worse, because functions using x_last in another thread will see it change underneath them unexpectedly, and worse still, could work with the data when it is incompletely copied from x

Upvotes: 2

Chr
Chr

Reputation: 965

import numpy as np

self.x_last = np.copy(x)

Upvotes: 3

Related Questions