Luca
Luca

Reputation: 10996

numpy: working on a subset of matrix

I have a 4x4 identity matrix in numpy and I want to scale the first 3 dimensions by a factor. Currently, the way I am doing it as follows:

# Some scaling factors passed as a parameter by the user
scale = (2, 3, 4)  
scale += (1,)  # extend the tuple
my_mat = scale * np.eye(4)

Out of curiosity, I was wondering if there is some way to do this without extending the tuple.

Upvotes: 2

Views: 87

Answers (1)

Hannes Ovrén
Hannes Ovrén

Reputation: 21831

This is quickly done with numpy broadcasting rules and indexing

A = np.eye(4)
scale = [2, 3, 4]

A[:3, :3] *= scale

Upvotes: 3

Related Questions