[SciPy-user] array vs matrix, converting code from matlab

Robert Kern robert.kern at gmail.com
Thu Apr 20 23:07:01 CDT 2006


David Cournapeau wrote:

>     To sum it up, what is the convention in scipy when a function 
> handles both scalar and arrays ? Is there an idiom to treat scalar and 
> arrays of size 1 the same way, whatever the number of dimensions arrays 
> may have ?

Very frequently, you can simply rely on the array broadcasting of the ufuncs and
basic operations to do the work for you. I can't find a simple description of
the broadcasting rules on the Web at the moment (big opportunity for a Wiki
page), but very basically:

In [1]: from numpy import *

In [2]: a = arange(20).reshape((4,5))

In [3]: a
Out[3]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [4]: a + 10
Out[4]:
array([[10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])

If you really do want scalars to be treated as arrays of size 1 (what
dimensionality?), then you can usually use one of the atleast_* functions:

In [5]: atleast*?
atleast_1d
atleast_2d
atleast_3d

In [6]: atleast_1d(10)
Out[6]: array([10])

In [7]: atleast_2d(10)
Out[7]: array([[10]])

In [8]: atleast_3d(10)
Out[8]: array([[[10]]])

-- 
Robert Kern
robert.kern at gmail.com

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco



More information about the SciPy-user mailing list