-3

I have a Problem with the simple insertion into a matrix in python: (I am not very python experienced)

matrix = numpy.zeros(shape=(len(10), len(10)), dtype=int)

Now I want to insert specific values to the matrix index, e.g. at line 1, column 1.

How do i do that? I already was on https://docs.scipy.org/doc/numpy but with the insert-method it does not work.

I just want a simple style like: matrix[1][1] = 17

It has to be a matrix in that style, because after insertion I have to do a singular value decomposition.

ThinkPad
  • 9
  • 1
  • 1
  • 2
  • 1
    `len(10)` throws a `TypeError`. – timgeb Nov 15 '17 at 11:43
  • I think what you want is `matrix = numpy.zeros(shape=(10, 10), dtype=int)` No need to do len(), this returns the length of some objects, like lists. – collector Nov 15 '17 at 11:46
  • 1
    oh yes thx... originally it was `matrix = numpy.zeros(shape=(len(myList), len(myOtherList)), dtype=int)` – ThinkPad Nov 15 '17 at 11:48
  • What's wrong with `matrix[1][1] = 17`? But note that Python is zero indexed to the first line and column will be matrix[0][0] – collector Nov 15 '17 at 11:53

1 Answers1

3

You're syntax is incorrect in the np.zeros constructor.

Here's what it should look like:

matrix = numpy.zeros(shape=(10, 10), dtype=int)

You can then set a value using normal array syntax:

matrix[1,4] = 10
print matrix

[[ 0  0  0  0  0  0  0  0  0  0]
 [ 0  0  0  0 10  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]]

P.S. as others have mentioned, Python references it's indexes from zero, not one. So to set row 4, column 5 the array indices would be matrix[3,4].

ccbunney
  • 2,282
  • 4
  • 26
  • 42
  • I cannot believe that... that works... I have already tried exactly that several times and the compiler always shows me an error like "there is no function assignment" or something like that. I am really confused about that... but now it works... Thx for you all! :-) – ThinkPad Nov 15 '17 at 12:32