MathGroup Archive 2008

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

Search the Archive

Re: SparseArray

  • To: mathgroup at
  • Subject: [mg92322] Re: SparseArray
  • From: "Steve Luttrell" <steve at>
  • Date: Sat, 27 Sep 2008 22:20:26 -0400 (EDT)
  • References: <gbl365$m5v$>

Have a look at the documentation for Band.

Here is an example of what you need to do:

n = 10;
{diagbelow, diag, diagabove} = RandomReal[{-1, 1}, {3, n}];
a = SparseArray[{Band[{1, 1}] -> diag,
    Band[{1, 2}] -> Most[diagabove],
    Band[{2, 1}] -> Most[diagbelow]}, {n, n}];

Stephen Luttrell
West Malvern, UK

"Uli Wuerfel" <uli.wuerfel at> wrote in message 
news:gbl365$m5v$1 at
> Hello,
> I want to create a SparseArray with the elements being zero except for the 
> diagonal elements and their direct neighbours. For those, I would like to 
> assign them a value from another list, depending on the index i.
> The code is like this:
> anz=150;
> kg=10^-3;
> dx=10^-5;
> delx={};
> For[i=1,i<=anz,
> delx=Append[delx,{i,dx}];
> i++];
> matr=SparseArray[{1,1}->-2*kg*delx[[1]][[2]],{i_,i_}/;1<i<anz->-2*kg*(delx[[i]][[2]]+delx[[i-1]][[2]]),{1,2}->kg*delx[[1][[2]],{i_,j_}/;i-j==1&&i>1->kg*delx[[i]][[2]],{i_,j_}/;j-i==1->kg*delx[[i-1]][[2]],{anz,anz}->-kg*(delx[[anz]][[2]]+delx[[anz-1][[2]])},{anz,anz}];
> Here delx is a very simple list, but later I would like to do the same 
> with a list with varying elements.
> The reason is that I would like to have a non-constant
> grid spacing in order to solve a differential equation with the 
> SparseArray and using LinearSolve.
> This works well as long as I assign constants to the SparseArray-item. If 
> I try to assign values from a list to the SparseArray-item, it does not 
> work.
> Can you help?
> Regards,
> Uli

  • Prev by Date: Re: How to debug init.m?
  • Next by Date: Re: copying a variable
  • Previous by thread: Re: SparseArray
  • Next by thread: How to debug init.m?