solve a pair of simultaneous equations in matlab

To solve a pair of simultaneous equations in MATLAB, you can use the solve function or the matrix approach.

  1. Using the solve function:
    • Create symbolic variables for the unknowns in your equations.
    • Define your equations using these symbolic variables.
    • Use the solve function to solve the equations. The solve function returns a structure with the solutions for the unknowns.

Here is an example:

main.m
% Define the unknown variables
syms x y

% Define the equations
eq1 = x + 2*y == 5;
eq2 = 3*x - y == 1;

% Solve the equations
sol = solve(eq1, eq2, x, y);

% Extract the solutions
x_sol = sol.x;
y_sol = sol.y;

% Display the solutions
disp(['x = ', char(x_sol)])
disp(['y = ', char(y_sol)])
292 chars
18 lines

The output will give you the solution for x and y.

  1. Using the matrix approach:
    • Represent the equations as a matrix equation of the form AX = B, where A is the coefficient matrix, X is the solution vector, and B is the constant matrix.
    • Use the backslash operator \ to solve the matrix equation.

Here is an example:

main.m
% Define the coefficient matrix
A = [1, 2; 3, -1];

% Define the constant matrix
B = [5; 1];

% Solve the matrix equation
X = A \ B;

% Extract the solutions
x_sol = X(1);
y_sol = X(2);

% Display the solutions
disp(['x = ', num2str(x_sol)])
disp(['y = ', num2str(y_sol)])
273 chars
17 lines

The output will give you the solution for x and y.

Both approaches will yield the same result: the values of x and y that satisfy the given equations. Choose the approach that suits your needs and preferences.

related categories

gistlibby LogSnag