Re: Set diagonal of square matrix
- To: mathgroup at smc.vnet.net
- Subject: [mg117093] Re: Set diagonal of square matrix
- From: Ray Koopman <koopman at sfu.ca>
- Date: Wed, 9 Mar 2011 07:02:01 -0500 (EST)
- References: <ikt5e6$t68$1@smc.vnet.net> <ikvohg$f4u$1@smc.vnet.net>
On Mar 6, 2:44 am, Ray Koopman <koop... at sfu.ca> wrote: > On Mar 5, 3:05 am, Szabolcs <szhor... at gmail.com> wrote: > >> 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. > > ReplacePart[{{0,0,0}, {0,0,0}, {0,0,0}}, {i_,i_} :> {a,b,c}[[i]] ] > > {{a,0,0}, {0,b,0}, {0,0,c}} Here's a somewhat simpler pre-6 one-liner: MapIndexed[If[Equal@@#2,vector[[#2[[2]]]],#1]&,matrix,{2}]