Question

I'm trying to construct the 2nd order operator matrix in matlab for an mxn matrix (n-2)xn more precisely.

I looked up diag but it only makes a square matrix. Just wondering for ideas.

Again, to reiterate,

D = diag(-2*ones(1,n-1),0)

will return -2 on the main diagonal but an mxn matrix does not have a main diagonal.

Was it helpful?

Solution

You are looking for spdiags:

>> n = 6; m = n-2;
>> D = full(spdiags(-2*ones(m,1),0,m,n))
D =
    -2     0     0     0     0     0
     0    -2     0     0     0     0
     0     0    -2     0     0     0
     0     0     0    -2     0     0

Or just use eye:

D = -2*eye(m,n)

Perhaps you want to combine several diagonals:

>> B = [ones(m,1) -2*ones(m,1) ones(m,1)];
>> D = full(spdiags(B,0:2,n-2,n))
D =
     1    -2     1     0     0     0
     0     1    -2     1     0     0
     0     0     1    -2     1     0
     0     0     0     1    -2     1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top