2

I am trying to create an numpy array(lets say A) of shape (a, b, 1, d) where d is unknown and changes according to the input I have. I have another array (lets say B) with shape (a, b, 1, 1). I want to append the values of B to A from the for loop. In matlab it can be easily done with:

a = zeros(a, b, 1, 1)
count = 0
for i = 1 : something
    ai = array of shape (a, b, 1, 1)
    count += 1
    a(:, :, 1, count) = ai
end

How can I achieve similar result in python ?

2
  • Have you tried anything in python yet? Commented Aug 24, 2017 at 3:39
  • Is something known at runtime? Commented Aug 24, 2017 at 3:45

2 Answers 2

4

MATLAB can grow matrices simply by indexing new values; numpy does not allow that. But you can concatenate A and B creating a new array with shape (a,b,1,d+1)

In [1187]: np.concatenate((np.ones((2,3,1,4)), np.ones((2,3,1,1))), axis=-1).shape

Out[1187]: (2, 3, 1, 5)

But if you want to do this multiple times, I'd suggest collecting the intermediate arrays in a list, and do one concatenate at the end. That's more efficient.

In [1189]: a = [np.zeros((2,3,1,1))]
In [1190]: for i in range(4):
      ...:     a.append(np.ones((2,3,1,1))*i)
      ...: a = np.concatenate(a, axis=-1)
      ...: 
In [1191]: a.shape
Out[1191]: (2, 3, 1, 5)

In [1192]: a
Out[1192]: 
array([[[[ 0.,  0.,  1.,  2.,  3.]],
        ....
        [[ 0.,  0.,  1.,  2.,  3.]]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. and if we want to remove the previous zeros that do not contain useful data (come from initialization), then we can do a = np.delete(a, 0, axis=-1). hope will be useful for some one. or it can be a = a[:, :, :, 1:].
0

numpy.append can be used, but it is not efficient as when used in a loop you get a code with quadratic time complexity. So the problem is "how to do it efficiently".

It seems that the standard overallocation technique to gain O(1) amortized complexity of the append operation is used in the dynarray package with is just light weight wrapper to the np.array.

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.