'Elementary matrices in Matlab

I am very new to MATLAB, and I am trying to create a numerical scheme to solve a differential equation. However I am having trouble implementing matrices. I was wondering if anyone can help with constructing a following NxN matrix?

Matrix to be constructed

I am sure there is a better way to implement, but the following works

N=10
tod=zeros(N)
for k=1:(N-1)
    tod(k, k+1)=-2
end
for k=1:(N-2)
    tod(k, k+2)=1
end
tod_2=zeros(N)
for k=1:(N-1)
    tod_2(k, k+1)=2
end
for k=1:(N-2)
    tod_2(k, k+2)=-1
end
tran=transpose(tod_2)
Final=tran+tod


Solution 1:[1]

One approach is to use Matlab's toeplitz command. In particular, you could do the following.

N = 10;    % example value; must have N >= 3

r = zeros(1,N);
r(2:3) = [-2,1];
c = -r;
R = toeplitz(c,r);

Alternatively, you could use the diag command. For instance,

d = [-2,1];
R = zeros(N);
for i = 1:2
    diag(R,i) = d(i);
    diag(R,-i) = -d(i);
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1