You can look at the code of gallery and if you do you'll find out that it calls tridiag in its private folder. What tridiag ends up doing in your case is:
matrix = full(spdiag([ [ones(nn-1, 1)*D; 0], ones(nn, 1)*(1-2*D), [0; ones(nn-1)*D] ], -1:1, nn, nn))
You could do the above directly to avoid the argument checking that gallery does but I doubt you'll see a meaningfull speed increase.
Other options:
matrix = diag(repmat(D, nn-1, 1), -1) + diag(repmat(1-2*D, nn, 1)) + diag(repmat(D, nn-1, 1);
This avoids going through a sparse matrix. No idea if it's any faster
- If nn is fixed you could precompute the diagonal indices and use these to fill the matrix:
subdiagidx = 2:nn+1:nn^2;
diagidx = 1:nn+1:nn^2;
superdiagidx = nn+1:nn+1:nn^2;
subsuperidx = [subdiagidx, superdiagidx];
matrix = zeros(nn);
matrix(subsuperidx) = D;
matrix(diagidx) = 1-2*D;