How do you concatenate Numeric
arrays?
Can you
concatenate
along "extra" dimensions like you can in IDL?
The answer to both questions is "yes"! Concatenation is done
using the Numeric
function concatenate
.
For instance, to concatenate one 1-D vector with another 1-D
vector:
>>> a = Numeric.array([1, 2, -6, 4, -8])
>>> b = Numeric.concatenate([a,a])
>>> b
array([ 1, 2, -6, 4, -8, 1, 2, -6, 4, -8])
But let's say you want to concatenate in "extra" dimensions.
(In IDL this is
done
using brackets.)
For instance, let's say you want array c
to be
a 2-D array, where each row is a duplicate of vector a
.
You could predeclare c
(using Numeric.array
),
but this won't work if the size of c
isn't known until
run-time.
An alternate method is to first use Numeric.reshape
to "inflate" the dimensions of a
to create an
"extra" dimension, then to use
Numeric.concatenate
(with the axis
keyword set to the "extra" dimensions) to finish the job.
Thus:
>>> a = Numeric.array([1, 2, -6, 4, -8])
>>> a.shape
(5,)
>>> a = Numeric.reshape(a,(a.shape[0],1))
>>> a.shape
(5, 1)
>>> c = Numeric.concatenate([a,a], axis=1)
We can see from analyzing c
(as a whole and in parts)
that c
is what we're looking for:
>>> c
array([[ 1, 1],
[ 2, 2],
[-6, -6],
[ 4, 4],
[-8, -8]])
>>> c[:,1]
array([ 1, 2, -6, 4, -8])
>>> c[3,:]
array([4, 4])
Notes: The idea of using array rank "inflation" comes from J. D. Smith's amazing Dimensional Juggling Tutorial for the IDL language.