MATLAB Answers

Creating a diagonal matrix with specific diagonal vectors

151 ビュー (過去 30 日間)
Pavinder Cheema
Pavinder Cheema 2017 年 12 月 9 日
回答済み: Alan 2020 年 4 月 20 日
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.

回答 (3 件)

John D'Errico
John D'Errico 2017 年 12 月 9 日
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 2017 年 12 月 9 日
編集済み: Andrei Bobrov 2017 年 12 月 9 日
out = gallery('tridiag',C,A,B); % here out - sparse matrix

Alan
Alan 2020 年 4 月 20 日
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];

Community Treasure Hunt

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

Start Hunting!

Translated by