solve a linear system of equations in matlab

In MATLAB, you can solve a linear system of equations using the left division operator \ or by invoking the linsolve function. Both methods are equivalent, but linsolve may be more convenient in some cases.

Consider the system of linear equations:

main.m
2x + 3y - z = 1
x - y + 2z = -3
3x + 2y - 4z = 4
49 chars
4 lines

To solve this system in MATLAB using the left division operator, create matrices for the coefficients of the variables and the constants:

main.m
A = [2 3 -1; 1 -1 2; 3 2 -4];
B = [1; -3; 4];
46 chars
3 lines

Then, you can solve the system by left dividing the A matrix by the B matrix:

main.m
X = A \ B
10 chars
2 lines

The output will be a column vector containing the values of [x; y; z] that satisfy the system of equations.

Alternatively, you can use the linsolve function to solve the system:

main.m
X = linsolve(A, B)
19 chars
2 lines

The output will be the same as before.

Note that if the A matrix is singular (i.e., its determinant is zero), then the system of equations has no unique solution. In this case, MATLAB will return a warning and may give you a least-squares solution instead.

related categories

gistlibby LogSnag