3

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?

1
  • Read the docstring for numpy.linalg.svd. You'll see that s is a 1d array holding the singular values. Also, numpy.transpose does not change an array in-place, so the line numpy.transpose(A) has no effect. Commented Dec 6, 2012 at 4:53

1 Answer 1

6

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.]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.