Creating a diagonal matrix with specific diagonal vectors

47 views (last 30 days)
Does anybody know how to create a matrix where only the main diagonal and the diagonal above and below it have values, the rest being zeros?
e.g
A=[1 2 3 4 5]
B=[5 6 7 8]
C=[9 10 11 12]
The main diagonal will be A and the diagonal above and below will be B and C respectively, in a 5x5 matrix.

Answers (3)

John D'Errico
John D'Errico on 9 Dec 2017
Learn yo use the tools for such a problem.
Here spdiags is the correct tool, creating a sparse matrix as a result.
help spdiags
Or, you could use my blktridiag tool, downloadable from the file exchange. blktridiag would also create the matrix as a sparse one. It is overkill for such a small problem however.
So for something as simple as a 5x5 matrix, the truly simplest way is to use diag to create THREE matrices, then adding them together. Thus create a mstrix with the main diagonal. Then create another with the sub-diagonal, with another call to diag. Finally create a matrix with the desired super-diagonal terms. Add the three matrices, and voila you are done.
I'll get you started:
A_sub = diag([9 10 11 12],-1);
A_sub
A_sub =
0 0 0 0 0
9 0 0 0 0
0 10 0 0 0
0 0 11 0 0
0 0 0 12 0
You can do the rest now. In fact, you can use the above scheme to solve your problem all in one line of code, if you wish.
Remember that for larger problems, you should be learning to use the sparse matrix tools though. They will be hugely more efficient both in terms of time and memory, especially for a tridiagonal matrix. (Well, they will be more efficient if you use them properly.)

Andrei Bobrov
Andrei Bobrov on 9 Dec 2017
Edited: Andrei Bobrov on 9 Dec 2017
out = gallery('tridiag',C,A,B); % here out - sparse matrix

Alan
Alan on 20 Apr 2020
Assuming the output matrix is square and N by N, this is what I would do.
Assume N=4, and I'd like to set the -1 diag to [1,2,3]
N = 4;
A = zeros(N,N);
A(diag(reshape(1:N*N,N,N),-1)) = [1 2 3];

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!