필터 지우기
필터 지우기

Creating a tridiagonal matrix

조회 수: 1,246 (최근 30일)
Aaron Atkinson
Aaron Atkinson 2019년 11월 11일
댓글: John D'Errico 2022년 12월 10일
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
David Goodmanson
David Goodmanson 2019년 11월 11일
Hi Aaron
check out the 'diag' function
Alex Treat
Alex Treat 2020년 10월 30일
coughs you were in the mec 103 class at CSU...

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
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:
2- Use diag :
>> 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
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
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
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
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 CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by