[Numpy-discussion] Shapes and sizes

Albert Strasheim fullung at gmail.com
Fri Feb 24 08:19:01 EST 2006


Hello all

I'm trying to write a function that takes a scalar, 0d-, 1d- or 2d array and
returns a scalar or an array obtained by performing some computations on
this input argument.

When the output of such a function is the same size as input, one can do the
following to preallocate the output array:

def f(a):
    arra = asarray(a)
    if a.ndim > 2:
        raise ValueError('invalid dimensions')
    b = empty_like(arra)
    # do some operations on arra and put the values in b
    return b

However, when the output array only depends on the size of a, but isn't
exactly the same, things seem to get more complicated.

Consider a function that operates on the rows of a (or the "row" if a is 1d
or 0d or a scalar). For every row of length n, the function might return a
row of length (n/2 + 1) if n is even or a row of length (n + 1)/2 if n is
odd. Thus, depending on the shape of a, empty must be called with one of
three different shapes.

def outsize(n):
    if n % 2 == 0: return n/2+1
    return (n+1)/2
if arra.ndim == 0:
    b = empty(())
elif arra.ndim == 1:
    b = empty((outsize(arra.shape[0]),))
else:
    b = empty((arra.shape[0],outsize(arra.shape[1]))

To me this seems like a lot of code that can could be simpler if there was a
function to get the size of an array that returns a useful value even if a
particular dimension doesn't exist, much like MATLAB's size, where one can
write:

b = zeros(size(a,1),outsize(size(a,2)));
function [m]=outsize(n)
    if mod(n, 2) == 0; m = n/2+1; else m =(n+1)/2; end

and still have it work with scalars, 1d arrays and 2d arrays.

Even if there were such a function for NumPy, this still leaves the problem
that the output is going to have the wrong shape for 0d and 1d arrays,
specifically (1,1) and (outsize(n),1) instead of () and (outsize(n),). This
problem is solved in MATLAB where there is no distinction between 1 and [1].

How do you guys deal with this problem in your functions?

Regars

Albert





More information about the NumPy-Discussion mailing list