0

I wrote the following code that does: (1) Generate root matrix of shape (3, 16), and (2) Generate 1000 binary vectors C such that each vector is added at the end of the root matrix iteratively one at a time.

The code is the following (python 2.7):

# STEP1: Generate root matrix 
root = [random.randint(0, 2 ** 16 - 1) for _ in range(16 - 1)]
root = [('{0:0' + str(16) + 'b}').format(x) for x in root]
root = np.asarray([list(map(int, list(x))) for x in root], dtype=np.uint8)

# STEP2: Generate 1000 binary vectors
C = [random.randint(0, 2 ** 16 - 1) for _ in range(1000)]
C = list(set(C))
C = [('{0:0' + str(16) + 'b}').format(x) for x in C]
C = np.asarray([list(map(int, list(x))) for x in C], dtype=np.uint8)

# Step3: For each vector of C, append it at the end of root matrix
for i in range(1000):
    batch = root[i:(i + (len(root)))]
    batch = np.append(batch, C[i])
    print(batch)
    # Continue to process batch after being extended by adding a new vector

The matrix C looks like this:

[[0 1 1 ..., 0 1 1]
 [1 0 1 ..., 1 0 1]
 [0 1 0 ..., 1 1 0]
 ..., 
 [1 1 0 ..., 1 0 0]
 [0 0 1 ..., 1 1 0]
 [1 1 1 ..., 1 1 1]]

The problem is that np.append(batch, C[i])merges all vectors into a single one but this is not what I want. My goal is to extend the root matrix from (3, 16) to be (4,16) by just adding a vector C[i] iteratively. How can I achieve that?

Thank you

1
  • Instead of using append, I recommend collecting the arrays you want to join in a list, and doing one np.array or concatenate. np.append is poorly written and too often confused with list append. Commented Feb 21, 2018 at 8:11

1 Answer 1

1

If you can swap this:

batch = root[i:(i + (len(root)))]
batch = np.append(batch, C[i])

For this:

batch = np.append(batch, [C[i]], axis=0)

axis allows you to append two matrices on a particular dimension. So we make C[i] into a matrix and append it in dimension 0.

I am not sure what the intention of this batch = root[i:(i + (len(root)))] is but it shortens batch to a matrix the size of root every time so it will not increase in size. It actually shrinks as you near the end of root.

Also C is not always 1000 vectors. Making them unique removes some.

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

1 Comment

Thank you very much. Very easy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.