Andy Perez
Andy Perez

Reputation: 327

Create a numpy array view for specific items

Is there a way to create a view for a numpy.ndarray that will only return specific items in a specific shape?

I'm working on a project with a material stress tensor matrix. I have created an ndarray sublcass that must maintain a 3x3 shape for its base. There is one module, however, that requires the tensor to be in Voigt notation. Unfortunately, this is not easily done by a simple reshape function because of the order of the entities in the matrix.

Notation Convention

I would like to be able to keep the single ndarray subclass and just create a separate view for the calculations that require this notation.

As of now, the best I've been able to come up with is creating a function that constructs and returns a new array from the instance's data property. It normally wouldn't be a big deal, but the calculations I need it for will need to be performed millions of times.

Upvotes: 1

Views: 334

Answers (1)

Martin
Martin

Reputation: 3385

you can pass list of indexes and extract only those values you are interested in

In this example, I create Eye matrix and from it I create View on diagonale

tensor = np.eye(3)

>>> diagonal_view = [i for i in range(3)], [i for i in range(3)]
>>> tensor[diagonal_view]
array([1., 1., 1.])

for your example in your matrix shape, you would want something like this

#             1. dimension , 2. dimension
voight_view = [0,1,2,1,2,0],[0,1,2,2,0,1] # voight notation # voight notation
>>> tensor[voight_view]
array([1., 1., 1., 0., 0., 0.])

In case you dont want reference, just use

array.copy()

But it seems that just pure assignment works too

new_array = tensor[voight_view]

Upvotes: 1

Related Questions