Creating a tridiagonal matrix
816 ビュー (過去 30 日間)
古いコメントを表示
I am currently trying to create a 500*500 matrix in matlab with diagonals a=-1, b=4, c=2. My teacher has said that the best way to go about it is using loops, but is there a coded in function to use?
2 件のコメント
採用された回答
Stephen23
2019 年 11 月 11 日
編集済み: Stephen23
2022 年 3 月 20 日
"My teacher has said that the best way to go about it is using loops"
Why on earth would they say that? Here are some non-loop aproaches:
1- See @giannit's comment: https://www.mathworks.com/matlabcentral/answers/490368-creating-a-tridiagonal-matrix#comment_1027546
>> N = 10;
>> a = -1;
>> b = 4;
>> c = 2;
>> M = diag(a*ones(1,N)) + diag(b*ones(1,N-1),1) + diag(c*ones(1,N-1),-1)
M =
-1 4 0 0 0 0 0 0 0 0
2 -1 4 0 0 0 0 0 0 0
0 2 -1 4 0 0 0 0 0 0
0 0 2 -1 4 0 0 0 0 0
0 0 0 2 -1 4 0 0 0 0
0 0 0 0 2 -1 4 0 0 0
0 0 0 0 0 2 -1 4 0 0
0 0 0 0 0 0 2 -1 4 0
0 0 0 0 0 0 0 2 -1 4
0 0 0 0 0 0 0 0 2 -1
3- indexing is reasonably simple:
>> M = zeros(N,N);
>> M( 1:1+N:N*N) = a;
>> M(N+1:1+N:N*N) = b;
>> M( 2:1+N:N*N-N) = c
M =
-1 4 0 0 0 0 0 0 0 0
2 -1 4 0 0 0 0 0 0 0
0 2 -1 4 0 0 0 0 0 0
0 0 2 -1 4 0 0 0 0 0
0 0 0 2 -1 4 0 0 0 0
0 0 0 0 2 -1 4 0 0 0
0 0 0 0 0 2 -1 4 0 0
0 0 0 0 0 0 2 -1 4 0
0 0 0 0 0 0 0 2 -1 4
0 0 0 0 0 0 0 0 2 -1
6 件のコメント
Arth Patel
2020 年 9 月 29 日
Can you please explain the second method a bit ? It's not clear to me how you're indexing a matrix using just one argument.
Stephen23
2020 年 10 月 30 日
"It's not clear to me how you're indexing a matrix using just one argument."
The second example uses linear indexing:
その他の回答 (1 件)
Jihen
2022 年 12 月 10 日
function[A]=remplissage(n)
R1=(-4)*ones(n-1,1);
R2=ones(n-2,1);
A=6*eye(n)+diag(R1,-1)+diag(R1,1)+diag(R2,2)+diag(R2,-2);
end
1 件のコメント
John D'Errico
2022 年 12 月 10 日
This does not actually answer the question, creating instead a matrix with 5 diagonals, so a penta-diagonal matrix.
参考
カテゴリ
Help Center および File Exchange で Operating on Diagonal Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!