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!