solving series of algebric linear equations using for loop
2 views (last 30 days)
Show older comments
Can anybody help me for writing a script file for solving these three alegberic equations (couple). I wrote a code, but I am interested to use a for loop for finding different ui. Right now the code just solve u1 u2 u3. I want something for finding ui (i=0:10). xi+1=xi+ih and h=0.5 (x0=0). In advance thank you so much!
Here is the code:
clc;
clear all;
close all;
syms u1 u2 u3
h=0.5;
x1=1.5;
x2=2;
x3=2.5;
x4=3;
u0=2;
u4=-1;
eqn1= u0-(2+h^2*(1-x1/5))*u1+u2-h^2*x1==0;
eqn2= u1-(2+h^2*(1-x2/5))*u2+u3-h^2*x2==0;
eqn3= u2-(2+h^2*(1-x3/5))*u3+u4-h^2*x3==0;
sol=solve([eqn1, eqn2, eqn3], [u1, u2, u3]);
u1sol=sol.u1
u2sol=sol.u2
u3sol=sol.u3
I have attached the problem to clarify the problem.
2 Comments
Answers (1)
Torsten
on 10 Mar 2023
Edited: Torsten
on 11 Mar 2023
N = 4;
xleft = 1.0;
xright = 3.0;
x = linspace(xleft,xright,N+1);
h = (xright-xleft)/N;
A = zeros(N+1);
b = zeros(N+1,1);
A(1,1) = 1;
for i = 2:N
A(i,i-1) = 1.0;
A(i,i) = -(2+h^2*(1-x(i)/5));
A(i,i+1) = 1.0;
end
A(N+1,N+1) = 1.0;
b(1) = 2.0;
b(2:N) = h^2*x(2:N);
b(N+1) = -1.0;
u = A\b
plot(x,u)
3 Comments
Torsten
on 11 Mar 2023
Edited: Torsten
on 11 Mar 2023
Yes, that's exactly what is implemented in the code.
You need to solve the linear system
A*u = b
for a tridiagonal matrix A with the elements
A(i,i-1) = 1.0;
A(i,i) = -(2+h^2*(1-x(i)/5));
A(i,i+1) = 1.0;
and the right-hand side vector
b(i) = h^2*x(i)
with the boundary values implemented as
A(1,1) = 1.0;
A(N+1,N+1) = 1.0;
b(1) = 2.0;
b(N+1) = -1.0;
which means u0 = 2 and u_(N+1)=-1.
I'm not sure whether the term x(i)/5 remains the same if N changes - maybe it becomes x(i)/N. But you better know the underlying problem of your algebraic system of equations.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!