There are MANY ways to solve this. I'm not at all sure what the final dimension of the matrix is expected to be. Is it 100x100? While you say that, the matrix you show is not square.
So, IF you want to create a square matrix with that pattern, then this will do the trick:
n = 10;
toeplitz([-1;zeros(n-1,1)]',[-1 1 -1,zeros(1,n-3)])
ans =
-1 1 -1 0 0 0 0 0 0 0
0 -1 1 -1 0 0 0 0 0 0
0 0 -1 1 -1 0 0 0 0 0
0 0 0 -1 1 -1 0 0 0 0
0 0 0 0 -1 1 -1 0 0 0
0 0 0 0 0 -1 1 -1 0 0
0 0 0 0 0 0 -1 1 -1 0
0 0 0 0 0 0 0 -1 1 -1
0 0 0 0 0 0 0 0 -1 1
0 0 0 0 0 0 0 0 0 -1
I've shown what it creates for n=10. Make n=100, and you get a 100x100 matrix.
Do you really want to create a non-square matrix? Still easy enough. You could use toeplitz again. Here, I create the matrix you showed in your example.
n = 7;
toeplitz([-1;zeros(n-3,1)]',[-1 1 -1,zeros(1,n-3)])
ans =
-1 1 -1 0 0 0 0
0 -1 1 -1 0 0 0
0 0 -1 1 -1 0 0
0 0 0 -1 1 -1 0
0 0 0 0 -1 1 -1
Pick n=100, to get a 98x100 array, IF that is really what you wanted.
Lots of other ways.
n = 5;
A = [-eye(n),zeros(n,2)] + [zeros(n,1),eye(n),zeros(n,1)] + [zeros(n,2),-eye(n)]
A =
-1 1 -1 0 0 0 0
0 -1 1 -1 0 0 0
0 0 -1 1 -1 0 0
0 0 0 -1 1 -1 0
0 0 0 0 -1 1 -1
Here is another, using gallery to create a circulant matrix.
n = 10;
A = gallery('circul',[-1 1 -1,zeros(1,n-3)]);
A((n-1):n,1:2) = 0
A =
-1 1 -1 0 0 0 0 0 0 0
0 -1 1 -1 0 0 0 0 0 0
0 0 -1 1 -1 0 0 0 0 0
0 0 0 -1 1 -1 0 0 0 0
0 0 0 0 -1 1 -1 0 0 0
0 0 0 0 0 -1 1 -1 0 0
0 0 0 0 0 0 -1 1 -1 0
0 0 0 0 0 0 0 -1 1 -1
0 0 0 0 0 0 0 0 -1 1
0 0 0 0 0 0 0 0 0 -1
Or, you could have used spdiags. Or sparse. Lets see, maybe I could get tricky? How about conv2?
n = 10;
A = conv2(diag(ones(1,n),1),[-1 1 -1],'same');
A(end) = -1
A =
-1 1 -1 0 0 0 0 0 0 0 0
0 -1 1 -1 0 0 0 0 0 0 0
0 0 -1 1 -1 0 0 0 0 0 0
0 0 0 -1 1 -1 0 0 0 0 0
0 0 0 0 -1 1 -1 0 0 0 0
0 0 0 0 0 -1 1 -1 0 0 0
0 0 0 0 0 0 -1 1 -1 0 0
0 0 0 0 0 0 0 -1 1 -1 0
0 0 0 0 0 0 0 0 -1 1 -1
0 0 0 0 0 0 0 0 0 -1 1
0 0 0 0 0 0 0 0 0 0 -1
So many ways to do this. I can think of at least a couple of other ways as I write this line.
Best Answer