# [Numpy-discussion] beginner question: rank-1 arrays

Emanuel Woiski woiski at gmail.com
Fri Nov 16 15:29:07 EST 2007

```On Nov 16, 2007 5:55 PM, Emanuel Woiski <woiski at gmail.com> wrote:

> Sorry for coming very late to the thread, but you mean something like:
> for i in range(len(cols):
>
> [sending too soon...]
>
> On Oct 9, 2007 4:36 AM, Sven Schreiber <svetosch at gmx.net > wrote:
>
> > Alan G Isaac schrieb:
> > > On Mon, 8 Oct 2007, Robin apparently wrote:
> > >> However in my code (I am converting from MATLAB) it is
> > >> important to maintain 2d arrays, and keep the difference
> > >> between row and column vectors.
> > >
> >
> Well, I have noticed that numpy doesn't care very much about rows and
cols. Mind you, if you slice along a col, you end up with a row - just try
it and see. But how can you evaluate an expression such as a[i] - b[j], for
all (i,j), with i for rows and j for cols?
The trick here is 'newaxis' . With 'newaxis' you have a temporary dimension
for a or b, without actually changing a or b shapes. Following the usual
meaning, the expression becomes: c = a[:,newaxis] - b
See:

>>> a = arange(3.)
>>> a
array([ 0.,  1.,  2.])
>>> b = a # just an example...
Now I want:
>>> c1 = zeros((3,3))
>>> for i in range(3):
for j in range (3):
c1[i,j] = a[i] - b[j]

>>> c1
array([[ 0., -1., -2.],
[ 1.,  0., -1.],
[ 2.,  1.,  0.]])

That's exactly the same as the one-liner:

>>> c2 = a[:,newaxis] - b
>>> c2
array([[ 0., -1., -2.],
[ 1.,  0., -1.],
[ 2.,  1.,  0.]])