Learn to use sparse. This is the kind of thing sparse does very well, AND it creates a sparse matrix, so the array will be stored efficiently when you start needing to solve bigger problems.
You can find my blktridiag on the File Exchange, which would actually do exactly what you need, at least in this specific case. Perhaps better might be to look at how it is coded, so you would learn to use sparse.
Or, if you wanted to solve this particular case simply and trivially, it could be done using spdiags, where you would pass it the three sets of diagonal elements. Again, one call to spdiags sill suffice, and the result will be a sparse matrix.
So for example, if a,b,c,d are row vectors, each of length n, lets see how you might build the result with one call to spdiags.
n = 4;
a = [1 2 3 4];
b = [5 6 7 8];
c = [1 3 5 7];
d = [2 4 6 8];
MATRIX = spdiags([0,b;[a,0]+[0,d];[c,0]]',[1 0 -1],5,5)
MATRIX =
(1,1) 1
(2,1) 1
(1,2) 5
(2,2) 4
(3,2) 3
(2,3) 6
(3,3) 7
(4,3) 5
(3,4) 7
(4,4) 10
(5,4) 7
(4,5) 8
(5,5) 8
full(MATRIX)
ans =
1 5 0 0 0
1 4 6 0 0
0 3 7 7 0
0 0 5 10 8
0 0 0 7 8
Finally, you can create this matrix simply enough using three calls to diag. Again, if you have ROW vectors of length n as a,b,c,d, then in one line, with no loops, we have:
MATRIX = diag([a,0] + [0,d]) + diag(b,1) + diag(c,-1);
MATRIX =
1 5 0 0 0
1 4 6 0 0
0 3 7 7 0
0 0 5 10 8
0 0 0 7 8
Again, see that the result is as expected, this time asa full matrix. That result from diag will be a full matrix, unless your vectors were stored in sparse form originally. In that case, the final matrix will also be sparse.
As I said, for more complicated problems, sparse itself is a trivial solution. Learn to use it, and your code will be the better for it. Best of all, no more need to throw in the towel.
Best Answer