# [SciPy-user] simple question about digonal matrices

Perry Greenfield perry at stsci.edu
Tue May 11 10:09:50 CDT 2004

```Karthikesh Raju wrote:

> Hi All,
>
> How does one do something as mundane as assigning value to a diagonal
> vector.
>
> D = array([1,2,3])
>
> D_with_zeros = array([[0,0,0],
>                      [0,0,0],
>                      [0,0,0]])
>
> now i want D in the diagonal of D_with_zeros, i was trying something like:
> numarray.diagonal(D_with_zeros) = D
>
> numarray is not happy with my assignment?
>
I don't believe that this is a numarray problem but python syntax
issue. You can't assign to a function call (that is the error
message you got, right?). It seems that you are asking for
a way of creating an array that is a view of the diagonal
of a matrix such that if you assign to elements of that diagonal
vector, the matrix will also be updated. With either Numeric
or numarray, it is possible to create such an array so you can
do that but it involves a couple steps (one could write a function
to do that for you in one step). It would have to work something
like this:

diagonalview(D_with_zeros)[:] = D

Note that you must use a slice assignment for this to work.
Note that this won't work for the diagonal function since
it returns a copy of the diagonal elements and so changing
those doesn't change the matrix.

You could define diagonalview as:

def diagonalview(arr)
return arr.flat[::arr.shape[1]+1]

(Note that this won't work for noncontinguous arrays and needs
some error checking)

Another approach usable with numarray is:

ind = arange(D_with_zeros.shape[1])
D_with_zeros[ind, ind] = D

```