Can someone explain why substitution not working in this code.Please explain.

7 views (last 30 days)
I don't know why substitution is not working to find values of X1 X2 and X3.I'm familiar with subs command but still there is an issue with this code:
% clc;clear;close;
%Solution using Gauss-Seidal method
%define all variables
syms x1 x2 x3
%write all linear equations
%In diagonally dominant form(If possible)
eqn1 = 5*x1 - 2*x2 + 3*x3 == -1;
eqn2 = -3*x1 + 9*x2 + x3 == 2;
eqn3 = 2*x1 - x2 - 7*x3 == 3;
%determine x1, x2, and x3 in symbolic form
x1 = solve(eqn1, x1)
x2 = solve(eqn2, x2)
x3 = solve(eqn3, x3)
%initialse values
X1 = 0; X2 = 0; X3 = 0;
%apply loop for fixed no. of iterations
for i = 1:7
%solve for X1
X1 = subs(x1,{x2,x3},{X2,X3})
%solve for X2
X2 = subs(x2,{x1,x3},{X1,X3})
%solve for X3
X3 = subs(x3,{x1,x2},{X1,X2})
end

Accepted Answer

Walter Roberson
Walter Roberson on 6 Oct 2021
You are solving the equations independently of each other. You solve eqn1 for x1, which leaves it expressed in terms of x2 and x3. You solve eqn2 for x2, which leaves it expressed in terms of x1 and x3 -- and so on.
To proceed iteratively, once you have solved eqn1 for x1, you should substitute that value of x1 into eqn2, transforming it into an equation in x2 and x3; solve for x2 which will be in terms of x3. Then substitute the x1 you found into eqn3 and then substitute the x2 into the result, to get eqn3 in terms of just x3; solve. Now do back substitution.
  3 Comments
Walter Roberson
Walter Roberson on 6 Oct 2021
When you do
x1 = solve(eqn1, x1)
it does not change any existing use of x1.
syms x1 x2 x3
eqn1 = 5*x1 - 2*x2 + 3*x3 == -1;
eqn2 = -3*x1 + 9*x2 + x3 == 2;
eqn3 = 2*x1 - x2 - 7*x3 == 3;
x1partial = solve(eqn1, x1)
x1partial = 
x2partial = solve(subs(eqn2, x1, x1partial), x2)
x2partial = 
x3sol = solve( subs(subs(eqn3, x1, x1partial), x2, x2partial), x3)
x3sol = 
x2sol = subs(x2partial, x3, x3sol)
x2sol = 
x1sol = subs(subs(x1partial, x2, x2partial), x3, x3sol)
x1sol = 
ajeet sahu
ajeet sahu on 6 Oct 2021
Edited: ajeet sahu on 6 Oct 2021
Thankyou very much.Now I can understand where I was doing mistake.Thankyou walter.

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!