numpy - 2D matrix/array - initialization like in Matlab...

Joshua Landau joshua.landau.ws at gmail.com
Mon Oct 15 17:50:17 EDT 2012


On 15 October 2012 22:09, someone <newsboost at gmail.com> wrote:

>
> See this:
>
> ==============================**============================
> In [5]: Dx = numpy.matrix('1 0 0; 0 0.5 -0.5; 0 -0.5 1.5')
>
> In [6]: Dx
> Out[6]:
> matrix([[ 1. ,  0. ,  0. ],
>         [ 0. ,  0.5, -0.5],
>         [ 0. , -0.5,  1.5]])
> ==============================**============================
>

<snip>


> Without having to manually change all the individual places using my
> variables (test is actually many variables, not just one but I think you
> should understand the problem now).
>
>
> How to initialize my array directly using variables ?
>
> It could also be that I wanted:
>
> test11 = 1
> test12 = 1.5
> test13 = 2
> test21 = 0
> test22 = 5
>
> Dx = numpy.matrix('test11 test12 test13; test21 test22 -0.5; 0 -0.5 1.5')
>
> Etc... for many variables...
>
> Appreciate ANY help, thank you very much!


 Well, I don't know that much on Numpy (I've only ever used the basic
stuff), but Ian Kelly's probably right. If you can't "just use" a list, why
don't you convert it?

def matrixstring2lists(string, lookup_chain):
>     stringmatrix = [substr.split() for substr in string.split(";")]



    return [
>         [
>             lookup_chain[item] if item.isidentifier() else eval(item)
>             for item in items
>         ]
>         for items in stringmatrix
>     ]



##### TESTS ######
> import builtins



## {{{ http://code.activestate.com/recipes/305268/ (r2)
> class Chainmap(dict):
>     """Combine multiple mappings for sequential lookup.



    For example, to emulate Python's normal lookup sequence:
>         import __builtin__
>         pylookup = Chainmap(locals(), globals(), vars(__builtin__))
>     """
>     def __init__(self, *maps):
>         self._maps = maps
>     def __getitem__(self, key):
>         for mapping in self._maps:
>             try:
>                 return mapping[key]
>             except KeyError:
>                 pass
>         raise KeyError(key)
> ## end of http://code.activestate.com/recipes/305268/ }}}


> test11 = 1
> test12 = 1.5
> test13 = 2
> test21 = 0
> test22 = 5



print(matrixstring2lists(
>     'test11 test12 test13; test21 test22 -0.5; 0 -0.5 1.5',
>     Chainmap(locals(), globals(), vars(__builtins__))
> ))


That said, calling "matrixstring2lists" requires inputting a mapping from
the local scope, so I don't see how it could get much simpler to call
(minus removing "vars(__builtins__)" unless you *really* want that for some
reason.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121015/39705743/attachment.html>


More information about the Python-list mailing list