Issue
I'm trying to populate an array by using 2D arrays with np.dstack.
m1 = np.array([[1,1],[1,1]])
m2 = np.array([[2,2],[2,2]])
m3 = np.array([[3,3],[3,3]])
lst = m1
lst = np.dstack((lst,m2))
lst = np.dstack((lst,m3))
What's the proper way to do it in a loop? I'm looking for something like
lst = np.empty(...)
for _
lst = np.dstack((lst,variable2Darray))
Solution
As other answers have shown, you can put the arrays in a list, and join them into a new array with one call:
In [173]: m1 = np.array([[1,1],[1,1]])
...: m2 = np.array([[2,2],[2,2]])
...: m3 = np.array([[3,3],[3,3]])
...:
...:
In [174]: alist = [m1,m2,m3]
In [175]: np.stack(alist)
Out[175]:
array([[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]],
[[3, 3],
[3, 3]]])
In numpy the first axis is the outer most. In contrast in MATLAB the last axis is outermost. So stack
(or np.array(alist)
) is the natural equivalent. But if you must join them on a new inner axis use:
In [176]: np.stack(alist,axis=2) # or np.dstack(alist)
Out[176]:
array([[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]]])
Or if you are creating the arrays one at a time, use a list append:
In [177]: alist = []
In [178]: for a in m1,m2,m3:
...: alist.append(a)
Perhaps the closest thing to your MATLAB is:
In [181]: arr = np.zeros((2,2,3),int)
In [183]: for i,m in enumerate([m1,m2,m3]):
...: arr[:,:,i] = m
for i=1:10
var = some2Dmatrix
A(:,:,i) = var;
end
In contrast to MATLAB numpy
does not simply add a layer when you index beyond the current size. I also suspect that MATLAB code actually hides some costly matrix resizing code. It's not something I did years ago when I used MATLAB professionally.
But to answer the question that we don't want to answer:
In [185]: arr = np.zeros((2,2,0),int) # your empty(?)
In [187]: for m in (m1,m2,m3):
...: arr = np.concatenate((arr, m[:,:,None]), axis=2)
In [188]: arr.shape
Out[188]: (2, 2, 3)
If you don't understand the details of this iteration, you probably shouldn't be trying to build a larger array with repeated concatenate
(or dstack
). You have to get the initial shape of arr
correct, and you have to get the right shape of the iteration array right. Plus this is making brand new arr
with each loop. That's costlier than list append.
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.