Jason Born
Jason Born

Reputation: 173

How to build a banded matrix on Matlab?

I am trying to build the banded matrix

C = [-1 1 ... 0]
    [ -1 1 ....]
    [..........]
    [0.....-1 1]

I managed to create a different banded matrix with

spdiags(ones(nx,1)*[1 -2 1],-1:1,nx,nx)

which looks like this:

C = [-2  1 ... 0]
    [ 1 -2 .....]
    [......... 1]
    [0..... 1 -2]

However, if I change [1 -2 1] to [-1 1], it doesn't work.

I get the error message

>> spdiags(ones(nx,1)*[-1 1],-1:1,nx,nx)
Index exceeds matrix dimensions.

Error in spdiags (line 102)
         a((len(k)+1):len(k+1),:) = [i i+d(k) B(i+(m>=n)*d(k),k)];

How can I fix this?

Upvotes: 1

Views: 803

Answers (3)

Wolfie
Wolfie

Reputation: 30046

Here's two pretty quick methods (although your approach could be sped up by removing the matrix multiplication).


You could just use a simple combination of eye (to create the diagonals) and zeros (to pad the extra column) to get the desired result:

nx = 5;
C = [-eye(nx), zeros(nx,1)] + [zeros(nx,1), eye(nx)];

% C = -1     1     0     0     0     0
%      0    -1     1     0     0     0
%      0     0    -1     1     0     0
%      0     0     0    -1     1     0
%      0     0     0     0    -1     1

Or use diag to create an offset diagonal, and subtract an eye matrix, you would need to removed the last row though. This gives the same result:

C = diag(ones(nx,1),1) - eye(nx+1);
C = C(1:end-1, :);

Upvotes: 1

dasdingonesin
dasdingonesin

Reputation: 1358

As doc spdiags will tell you, the second argument of spdiags specifies the diagonals that will be replaced in your matrix. As you want to modify different diagonals, you'll have specify those.

This will do what you want:

>> nx = 5;
>> C = spdiags(ones(nx,1)*[-1 1],0:1,nx,nx+1);
>> full(C)

ans =

    -1     1     0     0     0     0
     0    -1     1     0     0     0
     0     0    -1     1     0     0
     0     0     0    -1     1     0
     0     0     0     0    -1     1

Upvotes: 2

Luis Mendo
Luis Mendo

Reputation: 112679

A slighty more convoluted approach:

n = 5;                                   % desired number of columns
p = [-1 1];                              % pattern for each row
C = conv2(eye(n), flip(p), 'valid').';   % result

Upvotes: 1

Related Questions