0

I am trying to populate values of a i x j matrix, where each cell will have to values assigned to it [ , ].

I have tried many things. For example, the first cell I have tried

F[0][0]=[None,0]

and

F[0][0].append=[None,0]

and

F[0][0].append(None,0)

However the cells are still []. I'm assuming I must be making a stupid mistake, but if you can please help

2 Answers 2

1

Is there any reason not to use numpy.array in your code ? Your could initialize your (i,j) matrix (let's say i=2 and j=3 for instance) like that:

import numpy as np
F = np.zeros((2,3)) # initializes the matrix (fill it with 0)

Then if you want to fill for instance its first row (be carreful python indexes start at 0):

F[0,:] = [2,None,6]
>> array([[ 2., nan,  6.],
   [ 0.,  0.,  0.]])

It is always better for speed to correctly initialize your matrix, but would you need to add a row you can also yse numpy.append method (numpy.append):

np.append(F,[[5,-1,3]],axis=0) # axis=0 specifies that you want to add a row
>> array([[ 2., nan,  6.],
   [ 0.,  0.,  0.],
   [ 5., -1.,  3.]])

For vectors and matrices, numpy is much more convenient that embeded lists.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I was originally using numpy, but was told it would not work for this. Embedded lists is the data structure I need for this program.
Could you elaborate which kind of data you use, that makes numpy no fit ?
0

If you really want to work with initialized embeded lists, I guess you could use this:

F = [[None]*3]*2 # initializes your 2 lines and 3 colomns list, if needed
>> [[None, None, None], [None, None, None]]

F[1] = [0,None,2,3] # fills your second line (embeded list 1)
>> [[None, None, None], [0, None, 2, 3]]

F[0] = [5] # erases and changes your first line (embeded list 0)
>> [[5], [0, None, 2, 3]]

F.append([1,-1,None]) # adds a new list (which will be the embeded list 2)
>> [[5], [0, None, 2, 3], [1, -1, None]]

Given your post it seems that it covers what you are trying to achieve. Mind that if you primary defines your list by F=[[]], you will only have access to F[0] and to add another embeded list you will need to use list.append.

1 Comment

Thanks, I ended up figuring it out, but this was sort of what I ended up doing, thanks! Someone told me I needed to add "nones" to initialize the matrix(before I filled them with other values), which I was not doing.

Your Answer

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