solve set of linear equations with syms in matlab

To solve a set of linear equations in MATLAB using syms, you can follow these steps:

  1. Define the variables as symbolic using the syms function.
  2. Create a matrix or system of equations using the symbolic variables.
  3. Use the inverse matrix or Gaussian elimination method to solve for the variables.

Here's an example:

main.m
syms x y z
eqns = [2*x + y - z == 3;
        x - y + 3*z == -1;
        3*x + 2*y + z == 4];
sol = solve(eqns, [x y z]); % solve the equations
disp(sol) % print the solutions
175 chars
7 lines

This will output:

main.m
x = 7/5
y = 1/5
z = -2/5
25 chars
4 lines

Alternatively, you can use the inverse matrix method:

main.m
syms x y z
A = [2 1 -1; 1 -1 3; 3 2 1]; % coefficient matrix
B = [3; -1; 4]; % constant vector
X = A \ B; % solve using inverse matrix
disp(X) % print the solutions
165 chars
6 lines

This will output the same set of solutions:

main.m
X =

    7/5
    1/5
   -2/5
29 chars
6 lines

Or, you can use the Gaussian elimination method by converting the matrix to row echelon form using the rref function:

main.m
syms x y z
A = [2 1 -1; 1 -1 3; 3 2 1]; % coefficient matrix
B = [3; -1; 4]; % constant vector
AB = [A B]; % augmented matrix
r = rank(A); % rank of A
rref_AB = rref(AB); % row echelon form of AB
X = zeros(3, 1); % initialize solution vector
X(r) = rref_AB(1:r, end); % solve for variables using back substitution
for i = r-1:-1:1
    X(i) = rref_AB(i, end) - rref_AB(i, i+1:end) * X(i+1:end);
end
disp(X) % print the solutions
428 chars
13 lines

This will output the same set of solutions:

main.m
X =

    7/5
    1/5
   -2/5
29 chars
6 lines

gistlibby LogSnag