Goles
Goles

Reputation: 11799

Using numpy to Obtain Submatrix

I'm trying to do the following with numpy (python newbie here)

Create a zeroed matrix of the rigth dimensions

num_rows = 80
num_cols = 23
A = numpy.zeros(shape=(num_rows, num_cols))

Operate on the matrix

k = 5
numpy.transpose(A)
U,s,V = linalg.svd(A)

Extract sub-matrix

 sk = s[0:(k-1), 0:(k-1)]

Results on error

Traceback (most recent call last):
File "tdm2svd.py", line 40, in <module>
sk = s[0:(k-1), 0:(k-1)]
IndexError: too many indices

What am I doing wrong?

Upvotes: 3

Views: 12814

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113940

to answer your question s is only a 1d array ... (even if you did actually transpose it ... which you did not)

>>> u,s,v = linalg.svd(A)
>>> s
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>>

for selecting a submatrix I think this does what you want ... there may be a better way

>>> rows = range(10,15)
>>> cols = range(5,8)
>>> A[rows][:,cols]
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

or probably better

>>> A[15:32, 2:7]
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Upvotes: 6

Related Questions