Reputation: 1867
I want to use the Singular-Value-Decomposition of matrix A
.
If possible I would write:
V, S, W.T = np.linalg.svd(A)
But I can't initialise an array with its transposed. Now I have two questions:
As far as I understand the python internals there is no obvious workaround for this problem. Because the call of an attribute/method of W
requires the instance to be initialised.
One would need something as a constructor as @property
attribute.
If there is no obvious workaround, which one of the following options is better/more idiomatic.
Option 1:
V, S, tmp = np.linalg.svd(A)
W = tmp.T
Option 2:
V, S, W = np.empty(...), np.empty(...), np.empty(...)
V[:, :], S[:, :], W.T[:, :] = np.linalg.svd(A)
Upvotes: 2
Views: 186
Reputation:
Option 2 takes over 50% more time in my experiment. It's also harder to read.
Option 1 is good, but observe that W
will be a view of the array tmp
. This should not be a problem unless you do something that makes it one, like tmp[0,0] = 0
(which modifies W
too).
I would go with
W = np.linalg.svd(A)
W = W.T
which runs in the same time as the version with tmp
(and it still makes W a view) but does not create another name by which the same data can be accessed.
Upvotes: 3