Tridiagonal matrix (thomas algorithm)
이전 댓글 표시
hi.
i want to solve a second order, homogeneous differential equation by using tridiagonal matrix. can u help me?
so, i want only a general matlab code to solve like this equation.
because i am using "finite difference method"
채택된 답변
추가 답변 (2개)
Shantanu Vachhani
2015년 12월 24일
편집: Walter Roberson
2015년 12월 24일
%of the form AX=B
n=input('enter the order for the matrix');
for(i=1:n)
for(j=1:n)
a(i,j)=input('enter the element of coefficient matrix');
end
end
for i=1:n
r(i)=input('enter the RHS');
end
R(1)=0;
P=zeros(1,n);
Q=zeros(1,n-1);
R=zeros(1,n);
Y=zeros(1,n-1);
for i=1:n
P(i)=a(i,i);
end
for i=1:n-1
Q(i)=a(i,i+1);
end
for i=1:n-1
R(i+1)=a(i+1,i);
end
Y(1)=Q(1)/P(1);
for i=2:n-1
Y(i)=Q(i)/(P(i)-R(i)*Y(i-1));
end
W(1)=r(1)/P(1);
for i=2:n
W(i)=(r(i)-R(i)*W(i-1))/(P(i)-R(i)*Y(i-1));
end
x(n)=W(n);
for i=n-1:-1:1
x(i)=W(i)-Y(i)*x(i+1);
end
댓글 수: 2
John D'Errico
2018년 5월 12일
편집: John D'Errico
2018년 5월 12일
For someone who wants to use this code, remember that it will be very much slower than just using backslash. Looped student code is rarely efficient code. At best, it was an answer to a homework assignment. But no more than that.
For example, on a quick test with a 10k by 10k tridiagonal matrix, this looped code was roughly 10 times lower than just using backslash properly.
Mohammad Gohardoust
2019년 3월 1일
Thanks John for your complete answers in this page. In the case of tridiagonal matrix, I have tried what you have suggested and also tested the Thomas algorithm I have implemented. The results were comparable and even a bit to the favor of Thomas algorithm.
function h = Thomas(ld,md,ud,a)
% Solves linear algebraic equation where the coefficient matrix is
% tridiagonal. ld, md and ud stands for lower-, main, and upper-
% diagonal respectively. a is the answer matrix and h is the solution.
N = length(md) ;
w = zeros(N, 1) ; g = zeros(N, 1) ;
w(1) = ud(1)/md(1) ; g(1) = a(1)/md(1) ;
if isrow(ud)
ud = ud' ;
end
if isrow(ld)
ld = ld' ;
end
ud = [ud; 0] ; ld = [0; ld] ;
for i=2:N
w(i) = ud(i)/(md(i)-ld(i)*w(i-1)) ;
g(i) = (a(i)-ld(i)*g(i-1))/(md(i)-ld(i)*w(i-1)) ;
end
h = zeros(N, 1) ;
h(N) = g(N) ;
for i=N-1:-1:1
h(i) = -w(i)*h(i+1)+g(i) ;
end
end
Troy
2024년 10월 26일
0 개 추천
Solve by using Thomas Method
댓글 수: 1
Walter Roberson
2024년 10월 27일
I do not understand how your Answer will help the original poster?
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!