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

Bill Baxter wbaxter at gmail.com
Fri Apr 21 01:03:42 EDT 2006


On 4/21/06, David Cournapeau <david at ar.media.kyoto-u.ac.jp> wrote:
>
> Robert Kern wrote:
> > David Cournapeau wrote:
> >
> 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


To handle the first two cases (scalar, and call scalar on every element),
you should be able to use 'numpy.frompyfunc' to create a version of your
scalar function that automatically works that way.

def plusone(v):
    return v+1
uf = numpy.frompyfunc(plusone,1,1)

>>> uf(1)
2
>>> uf([1,2,3])
array([2, 3, 4], dtype=object)


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 ?


Looks like atleast_1d doesn't copy the data, so yes, it should be fast.

a = numpy.array([1,2,3,4])
b = numpy.atleast_2d(a)
a
array([1, 2, 3, 4])
b
array([[1, 2, 3, 4]])
a[1]=0
a
array([1, 0, 3, 4])
b
array([[1, 0, 3, 4]])

--
William V. Baxter III
OLM Digital
Kono Dens Building Rm 302
1-8-8 Wakabayashi Setagaya-ku
Tokyo, Japan  154-0023
+81 (3) 3422-3380
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20060421/fd87bb00/attachment.html>


More information about the SciPy-User mailing list