# [SciPy-User] Matrix indexing and updating

Emanuele Olivetti emanuele@relativita....
Mon Nov 1 17:57:31 CDT 2010

I don't know much about scipy.matrix since I don't use it.
But I guess it is more or less the same. So:
----
In [1]: import numpy as np

In [2]: import scipy as sp

In [3]: mat = sp.matrix(np.arange(100).reshape(10,10))

In [4]: rows = [[1],[3],[4]]

In [5]: columns = [4,5,9]

In [6]: mat[rows,columns]
Out[6]:
matrix([[14, 15, 19],
[34, 35, 39],
[44, 45, 49]])

In [7]: mat[rows,columns] += np.arange(9).reshape(3,3)

In [8]: mat[rows,columns]
Out[8]:
matrix([[14, 16, 21],
[37, 39, 44],
[50, 52, 57]])

In [9]: mat
Out[9]:
matrix([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
[10, 11, 12, 13, 14, 16, 16, 17, 18, 21],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 37, 39, 36, 37, 38, 44],
[40, 41, 42, 43, 50, 52, 46, 47, 48, 57],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])
------

Note the difference between using
rows = [[1],[3],[4]]
and
rows = [1,3,4]

Hope this helps,

Emanuele

On 11/01/2010 11:43 AM, Luca Manini wrote:
>>>>>> "Emanuele" == Emanuele Olivetti<emanuele@relativita.com>  writes:
>>>>>>
>      Emanuele>  Hi Luca, If I understand you problem correctly, maybe
>
>      It helps a little, but:
>
>      1) you are using numpy.ndarray instead of scipy.matrix.  I have
>         not grasped the difference yet, apart for the annoying fact
>         that a 1xN matrix is not a vector and still has two indices
>         (and that makes the code less "explicit").
>
>         For exmple:
>
>      In [58]: import scipy
>
>      In [59]: v = scipy.matrix(range(5))
>
>      In [60]: v
>      Out[60]: matrix([[0, 1, 2, 3, 4]])
>
>      In [61]: for x in v:
>         ....:        print x
>         ....:
>      [[0 1 2 3 4]]
>
>      In [62]:
>
>      In [63]: z = v.tolist()[0]
>
>      In [64]: z
>      Out[64]: [0, 1, 2, 3, 4]
>
>      In [65]: for x in z:
>         ....:     print x
>         ....:
>         ....:
>      0
>      1
>      2
>      3
>      4
>
>
>      2) you set the submatrix values to 1, but what I need is to "add"
>         to the submatrix the values that come from an (equal sized)
>         matrix.
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>