Asked by Mehmet
on 11 Mar 2011

hi.

i want to solve a second order, homogeneous differential equation by using tridiagonal matrix. can u help me?

example: http://img846.imageshack.us/i/diffeq.jpg/

so, i want only a general matlab code to solve like this equation.

because i am using "finite difference method"

*No products are associated with this question.*

Answer by John D'Errico
on 11 Mar 2011

Why not just build it as a sparse matrix using spdiags, then solve using backslash? It will be quite fast for a tridiagonal matrix, and you won't need to write any solver at all.

For example, I won't bother to do more than create a random tridiagonal matrix, rather than building one directly from your equation, but the time is all that matters.

n = 100000; A = spdiags(rand(n,3),-1:1,n,n); b = rand(n,1); tic,x = A\b;toc Elapsed time is 0.023090 seconds.

So to solve a system with 1e5 unknowns took me .023 seconds, with virtually NO time invested to write anything.

Mehmet
on 11 Mar 2011

i am very new on matlab and didnt understood anything from your answer. But thank for your answer.i dont know anything about backslash.

i need only general example code (a basic application) like my differential equation.this example should solve second order, homogeneous diff eq. i think it was been solved by using "thomas algorithm" but if there another solution you can give me as .m file. i need this solution immediately.

thank for all John

John D'Errico
on 11 Mar 2011

I gave you the solution as m-code. If you don't understand it, then it is high time to start reading the tutorials. Read the help for slash, or for linsolve, and for spdiags.

Answer by Shantanu Vachhani
on 24 Dec 2015

Edited by Walter Roberson
on 24 Dec 2015

%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

Related Content

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
## 0 Comments