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: [mg116986] Re: Set diagonal of square matrix
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Sun, 6 Mar 2011 05:45:07 -0500 (EST)

Hi Szabolcs,

Here are some matrix and vector:

mat =  RandomInteger[{1, 1000}, {1000, 1000}];
vec = Range[1000];

I don't see why not use procedural code here - it is simple and fast:

Do[mat[[i, i]] = vec[[i]], {i, Length[mat]}]; // Timing

{0., Null}

If matrices are numerical, you can compile it and get it very much faster
still.

For very large sparse matrices you may have more luck with using
SparseArrays,especially
if the new diagonal is also sparse (has many zeros).

Regards,
Leonid


On Sat, Mar 5, 2011 at 2:04 PM, Szabolcs <szhorvat 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.
>
>


  • Prev by Date: Re: Mathematica Navigator in Documentation Center - high processor load
  • Next by Date: random line in a very large file
  • Previous by thread: Re: Set diagonal of square matrix
  • Next by thread: Re: Set diagonal of square matrix