MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

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


  • Prev by Date: How to avoid repeated calculation in NDSolve ?
  • Next by Date: Re: Prepending Data to a File
  • Previous by thread: Re: Set diagonal of square matrix
  • Next by thread: Re: Set diagonal of square matrix