[Numpy-discussion] Detect subclass of ndarray
Bill Baxter
wbaxter at gmail.com
Sat Mar 24 04:54:49 EDT 2007
On 3/24/07, Charles R Harris <charlesr.harris at gmail.com> wrote:
>
>
> On 3/23/07, Anne Archibald <peridot.faceted at gmail.com> wrote:
> > On 23/03/07, Charles R Harris <charlesr.harris at gmail.com> wrote:
> > > Anyone,
> > >
> > > What is the easiest way to detect in python/C if an object is a subclass
> of
> > > ndarray?
> >
> > Um, how about isinstance or issubclass? (if you want strictness you
> > can look at whether x.__class__ is zeros(1).__class__)
>
> What I am trying to do is figure out the easiest way to fix up matrix
> multiplies so they work properly. For instance, the following gives the
> wrong result:
>
> In [15]: I = matrix(eye(2))
>
> In [16]: I*ones(2)
> Out[16]: matrix([[ 1., 1.]])
>
> where the output should be a column vector. In order to do that, I need to
> reshape the rh multiplicand before __mul__ calls the dot function. There is
> also this problem
I have a little 'ascol()' function I use for that kind of situation.
In your case I'd say
I * ascol(ones(2))
---------------------
def ascol(v):
"""Turns 1-d inputs into a column vectors.
For all other inputs acts like atleast_2d.
(Q: Should this also transpose any (1xN)'s to be columns? The
current thinking is if you have a 1-d then you haven't really
decided whether it's a row or col, and this method is asserting
that it should be a column. But if it's already a 2-d row, then
it's probably a row for a reason, and you should transpose it
explicitly if you want a column.)
"""
arr = numpy.array(v,copy=False,subok=True)
if arr.ndim<2:
return numpy.transpose(numpy.atleast_2d(arr))
else:
return arr
---------------------
--bb
More information about the NumPy-Discussion
mailing list