Re: Set diagonal of square matrix
- To: mathgroup at smc.vnet.net
 - Subject: [mg116989] Re: Set diagonal of square matrix
 - From: Peter Pein <petsie at dordos.net>
 - Date: Sun, 6 Mar 2011 05:45:40 -0500 (EST)
 - References: <ikt5e6$t68$1@smc.vnet.net>
 
Am 05.03.2011 12:05, schrieb Szabolcs:
> Dear MathGroup members,
>
> Is there any simple way to set the diagonal of a square matrix to a
> vector (of appropriate length)?  Of course there are ways to do it,
> but I was wondering if there was a simple, one-line way.
>
Hi,
an almost obvious method is using Tr and DiagonalMatrix:
In[1]:= MatrixForm[mat=RandomInteger[{-5,5},{5,5}]]
	vdiag=Range[5];
Out[1]//MatrixForm=
(-1	-1	-5	3	2
  1	-2	1	0	-5
  2	-1	3	1	2
  4	-3	-1	-5	-4
  0	1	-3	4	1
)
In[3]:= MatrixForm[mat+=DiagonalMatrix[vdiag-Tr[mat,List]]]
Out[3]//MatrixForm=
(1	-1	-5	3	2
  1	2	1	0	-5
  2	-1	3	1	2
  4	-3	-1	4	-4
  0	1	-3	4	5
)
hth,
Peter