문제

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.

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top