[Numpy-discussion] Shapes and sizes
fullung at gmail.com
Fri Feb 24 08:19:01 CST 2006
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:
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
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.
if n % 2 == 0: return n/2+1
if arra.ndim == 0:
b = empty(())
elif arra.ndim == 1:
b = empty((outsize(arra.shape),))
b = empty((arra.shape,outsize(arra.shape))
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
b = zeros(size(a,1),outsize(size(a,2)));
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 .
How do you guys deal with this problem in your functions?
More information about the Numpy-discussion