Reputation: 123
This is my code to solve equation systems.
Something is wrong with my code but I can't fix it.
D=1
E=2
F=3
syms a b c;
S= solve('a+b-c=D','2*+b-3*c=E','a-2*b=F')
S = [S.a S.b S.c]
Upvotes: 0
Views: 1229
Reputation: 30156
Fixing your problem with symbolic solving
Looking at the documentation for solve
, you can see an example for how to input equations to the solve
function. They should not be strings (like you have done), but instead they should be equations using ==
in place of =
.
Docs example:
syms x solx = solve(sin(x) == 1,x)
Applying this to your system:
D=1; E=2; F=3;
syms a b c;
S = solve(a+b-c==D, 2*b-3*c==E, a-2*b==F);
S = [S.a S.b S.c];
% Ouput:
% S = [5/7, -8/7, -10/7]
Note, in the above example I have replaced *+
in your second equation with *
. Use either *
or +
, but not both! I'm assuming this was a typo, it is not the root of your problems.
Another option without using symbolic maths
You can solve this without the symbolic math toolbox too. Your equations can be written as
1a + 1b - 1c = D
0a + 2b - 3c = E
1a - 2b + 0c = F
Which, in matrix form, is the same as
1 1 -1 a D
0 2 -3 * b = E
1 -2 0 c F
Using matrix operations, this can be solved by pre-multiplying both sides by the inverse of the 3x3 matrix. In MATLAB, getting this result is easy:
% Set up 3x3 matrix of coefficients
coeffs = [1 1 -1; 0 2 -3; 1 -2 0];
% Set up left hand side vector
DEF = [1; 2; 3];
% Solve
S = coeffs\DEF;
% Ouput
% S = [0.7143, -1.1429, -1.4286]
This output is the same as before, although clearly not in exact fractional form, since that is inherited from a
,b
and c
being symbolic.
Edit: Some things to consider about solving matrix equations in MATLAB, as prompted by Dev-iL's comment...
\
operator I've used above is shorthand for MATLAB's mldivide
function
x = mldivide(A,B)
is an alternative way to executex = A\B
\
works:
If A is a square matrix,
A\B
is roughly equal toinv(A)*B
, but MATLAB processesA\B
differently and more robustly.
The versatility of mldivide in solving linear systems stems from its ability to take advantage of symmetries in the problem by dispatching to an appropriate solver.
In summary:
Whilst mathematically "pre-multiplying by the inverse of the coeffs
matrix" gives the solution to the system, using the backslash operator (a.k.a mldivide
) is the MATLAB-esque way to solve this problem.
How does this extension relate to your original question? Hopefully you are better informed about which methods can be used for this problem. In particular, know that (unless needed for your particular situation) you can do this task easily (in less lines, quicker) without relying on MATLAB's symbolic math toolbox.
Upvotes: 5