[Numpy-discussion] matlab to numpy help

Eric Firing efiring@hawaii....
Sun Dec 23 13:26:00 CST 2007


Gabriel J.L. Beckers wrote:
> I found a matlab script that I want to translate into numpy, but have
> difficulties with understanding indexing in matlab. I haven't used
> matlab very much and I was hoping that someone could help with the
> following:
> 
> It says:
> 
> 	Uns = ones(1,m);
> 	
> ... and then later
> 
> 	Xijm(:,Uns);
> 
> 
> m is a positive integer. The problem is that Xijm should be a
> 1-dimensional array (I think), so what is Uns doing in the second
> statement? Is this some way to expand Xijm into a second dimension? What
> would be a numpy equivalent?

What this is doing depends on exactly what Xijm is.  Matlab started out 
with 2-D arrays only--*everything* was a 2-D array (matrix) of 
double-precision numbers.  (Even strings were represented as 
double-precision matrices.) Later, support for more dimensions was 
tacked on, but a vector in Matlab is still a 2-D array, and by default 
it is a single row:

 >> Xijm = [2,3,4]
Xijm =
      2     3     4
 >> size(Xijm)
ans =
      1     3
 >> Xijm(:,ones(1,2))
ans =
      2     2

To make a row into a column, you can transpose it:

 >> XijmT = Xijm.'
XijmT =
      2
      3
      4
 >> XijmT(:,ones(1,2))
ans =
      2     2
      3     3
      4     4

Numpy is much more general, and supports arrays of any number of 
dimensions right from the start.

My guess is that in your Matlab application, X is a column (XijmT), as 
in the second example above, and the indexing is repeating the columns 
as shown.  Usually this is done to facilitate an array operation with 
another array that, in this example, has shape (3,2).  In numpy it is 
not necessary to make a new array with the columns repeated because 
broadcasting achieves the same result more efficiently:

In [1]:import numpy

In [2]:XijmT = numpy.array([2,3,4])

In [3]:XijmT.shape
Out[3]:(3,)

In [4]:A = numpy.arange(6)

In [5]:A.shape = 3,2

In [6]:A
Out[6]:
array([[0, 1],
        [2, 3],
        [4, 5]])

In [9]:XijmT[:,numpy.newaxis] + A
Out[9]:
array([[2, 3],
        [5, 6],
        [8, 9]])

The indexing with numpy.newaxis makes a 2-D view of the 1-D array, 
allowing the column dimension to be broadcast to match that of A.

Eric

> 
> Gabriel
> 
> 
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion



More information about the Numpy-discussion mailing list