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

David Cournapeau david at ar.media.kyoto-u.ac.jp
Thu Apr 20 23:32:33 CDT 2006

```Robert Kern wrote:
> 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]])
>
>
I understand those cases, this is pretty similar to matlab, so I am used
to it. But my problem is different (or maybe not ?)
> 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:
>
>
This looks exactly like what I am looking for. My problem for my
function is the following (pseudo code):

foo(x, mu, va):

if mu and va scalars:
call scalar_implementation
return result
if mu and va rank 1:
call scalar implementation on each element
if mu rank 1 and va rank 2:
call matrix implementation

and assumed all arguments are always rank 2, even if they are "scalar"
(size 1), a bit like in numpy.linalg, if I understood
correctly (calling numpy.linalg.inv(1) does not work). It looks like
those atleast* methods should do the work.

Actually, my problem is pretty similar to implementing wrapper around
numpy.linalg.inv which works in scalar case and rank 1 (assuming rank 1
means diagonal) cases. Are those atleast* functions expensive ? For
small size arrays, I don't care too much, but in the case of a big array
of rank 1 converted to a rank 2 array, does those function need to copy
the data ?

David

```