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!