Padding numbers in a numpy array in sets 1024
I have a large array with increasing elements as follows
A = [512,2560,3584,5632,....]
Elements are always spaced at least 1024 apart.
Let's say I need to convert this above array into one below, where for each element of the original matrix A I take a range of values ββfrom A[n]
to A[n]+1024
(one step at a time) and they become the values ββof the new matrix as follows:
A2 = [512,513,514,...,1535,2560,2561,2562,...3583,....]
The way I solved the problem was to iterate over the original matrix A, create a range of values ββbetween A[0]
and A[0]+1024
(for example), allocate them into a new array, and so on. The code is below. The convention is for A as a seed matrix
seed = 0 A2 = np.empty(len(A)*1024,) for ind in range(len(A)): A2[seed:seed+1024] = np.arange(A[ind],A[ind]+1024) seed = seed+1024;
I am getting the answer I want, but I wonder if this is the best way to do it. I am a Matlab user switching to python and numpy
, and I haven't used optimization yet numpy
. I appreciate any help.
source to share
You can use broadcasting
-
(A[:,None] + np.arange(1024)).ravel()
Example run -
# Input array
In [433]: A = np.array([512,2560,3584,5632])
# Add ranged numbers in a broadcasted way for elementwise addition
In [434]: A[:,None] + np.arange(1024)
Out[434]:
array([[ 512, 513, 514, ..., 1533, 1534, 1535],
[2560, 2561, 2562, ..., 3581, 3582, 3583],
[3584, 3585, 3586, ..., 4605, 4606, 4607],
[5632, 5633, 5634, ..., 6653, 6654, 6655]])
# Finally flatten those for final output
In [435]: (A[:,None] + np.arange(1024)).ravel()
Out[435]: array([ 512, 513, 514, ..., 6653, 6654, 6655])
Alternatively with np.add.outer
-
np.add.outer(A,range(1024)).ravel()
Equivalent MATLAB version:
For reference, a version of MATLAB using the equivalent broadcasting
c bsxfun
and with column order in mind would look something like this:
>> A = [512,2560,3584,5632]; >> sums = bsxfun(@plus, A, [0:1023].'); >> [sums(1:3,1) ; sums(end-2:end,1)].' ans = 512 513 514 1533 1534 1535 >> [sums(1:3,2) ; sums(end-2:end,2)].' ans = 2560 2561 2562 3581 3582 3583 >> [sums(1:3,3) ; sums(end-2:end,3)].' ans = 3584 3585 3586 4605 4606 4607 >> [sums(1:3,4) ; sums(end-2:end,4)].' ans = 5632 5633 5634 6653 6654 6655 >> out = reshape(sums,1,[]); >> [out(1:3) out(end-2:end)] ans = 512 513 514 6653 6654 6655
source to share