MATLAB from scratch (2) — scripts, systems of equations and syms (what the AG assignments ask for)
In the second assignment I had a system that on paper had infinitely many solutions. I moved it to MATLAB, typed x = A\b and got a perfectly ordinary vector, with no warning at all: MATLAB had given me one of the infinitely many solutions and I wrote “unique solution”. The backslash solves, but it does not tell you how many solutions there are; that is what rank and rref are for. This article is the second part of MATLAB from scratch and it is about exactly that: how you work in the AG assignments.
If you missed the first part (vectors, matrices and the dot in .*), it is in MATLAB from scratch: the Command Window, vectors and matrices. Everything here also works in the site’s MATLAB playground, syms included.
In a nutshell: to solve a system in MATLAB you compare rank(A) with rank([A b]) and with the number of unknowns (Rouché-Frobenius), look at the reduced echelon form with rref([A b]) and, if the solution is unique, compute it with x = A\b. Problems with parameters are done with syms.
Table of Contents
Before you start. All you need is the first part (writing a matrix with brackets and semicolons) and having seen Gauss on paper: subtracting rows to make zeros. We build the idea of rank here, with the article’s own system. The order: where you write the code (the script); the questions every system asks, each with its command (is there a solution?, rank; what is it?, rref and A\b); what to do when there are infinitely many (null); det, inv and eig; and how to work with a letter (syms). If you get lost, go back to my story: the whole article is there so you never write “unique solution” when it is not.
Scripts: your assignment in one file
Typing commands one by one in the Command Window is fine for trying things, but an assignment is done in a script: a .m file with all the commands, which you save and can run again whenever you want.
- On the HOME tab, click New Script. The editor opens.
- Write the commands, one per line, just as in the Command Window.
- Save it with a name without spaces or accents that does not start with a number:
tp2_system.mis fine;TP 2 system.mis not. - Click Run (or F5). The output appears in the Command Window and the variables in the Workspace.
Comments and sections
Everything after % is a comment. A line starting with %% opens a section: Ctrl + Enter runs only the section the cursor is in, which is very handy for working part by part.
%% Part a: the system A = [2 -1 0; 1 3 -1; 1 0 1]; % coefficients b = [-7; 5; 0]; % right-hand side %% Part b: the solution x = A \ b
Output:
x =
-2
3
2
Naming your script like a MATLAB function (rank.m, det.m, solve.m). When you do, your file “shadows” the real function and suddenly rank stops working in all your scripts. If it happens, rename the file.
Start your scripts with clear, clc. clear deletes the variables left over from before and clc clears the Command Window, so what you see is only this script.
Script or Command Window: what really changes
The commands are the same in both places. A script is saved, it runs in full with one Run and, if there is a mistake, you change that line and not everything. The surprising part is that a script has no variables of its own: it uses the ones in the Workspace and leaves its own there. That is why the clear from the tip above is not a quirk: without it, a script may only work because an old A was still alive.
This is what happens, line by line, when you click Run on the example script:
| Line | What happens | Why |
|---|---|---|
%% Part a: the system | Nothing runs | %% opens a section; the rest of the line is a comment |
A = [2 -1 0; 1 3 -1; 1 0 1]; | A appears in the Workspace, but not on screen | The ; at the end silences the output; % coefficients is ignored |
b = [-7; 5; 0]; | b appears as a column with 3 rows | The ; inside separate rows |
%% Part b: the solution | Nothing runs | The second section starts |
x = A \ b | x = -2 3 2 appears in the Command Window | It has no ;, so MATLAB shows the result |
Check you’ve got it: you open MATLAB, put the cursor in part b and press Ctrl + Enter without having run anything before. What happens?
You get an error: Unrecognized function or variable 'A'. Step by step: Ctrl + Enter runs only the section the cursor is in, the line x = A \ b. It needs A and b, which are created in part a, and the Workspace is empty because you have just opened MATLAB. If you run part a first, or click Run, it works.
Solving a system step by step
Here is the method used in AG: first classify the system with Rouché-Frobenius and then solve it. We carry on with the system from the previous example:
Before the commands: classify it yourself
Before letting MATLAB answer, do it once by hand: it is the way to stop rank being a magic word. The augmented matrix (coefficients and, after the bar, the right-hand side), with Gauss:
- Row 1: (2, −1, 0 | −7)
- Row 2: (1, 3, −1 | 5)
- Row 3: (1, 0, 1 | 0)
| Step | Operation | Resulting row | Why |
|---|---|---|---|
| 1 | Swap row 1 and row 3 | On top, (1, 0, 1 | 0) | It starts with 1: the pivot is ready without dividing |
| 2 | Row 2 − row 1 | (0, 3, −2 | 5) | Below the pivot there is a 1: subtract the row as it is |
| 3 | Row 3 − 2 · row 1 | (0, −1, −2 | −7) | The old first row starts with 2: subtract twice the row |
| 4 | 3 · row 3 + row 2 | (0, 0, −8 | −16) | To remove the y: 3 · (−1) + 3 = 0 |
No row has become all zeros: the three equations each add something new. That number, how many rows survive Gauss, is the rank.
Now think about what could have come out:
- A row (0, 0, 0 | 0). That equation said nothing new: the rank drops and some unknown is left free.
- A row (0, 0, 0 | 5). It says 0 = 5: impossible. In the A part it is all zeros and in the augmented matrix it is not, so the augmented matrix has one more rank. No solution.
- Neither, as here: as many rows with a pivot as unknowns. A unique solution.
That is Rouché-Frobenius, without the names: the rank of A against the rank of the augmented matrix tells you whether there is a solution, and against the number of unknowns, how many. MATLAB counts those rows for you.
1. The ranks: does it have a solution, and how many?
p = rank(A) q = rank([A b]) n = size(A, 2)
Output:
p =
3
q =
3
n =
3
[A b] is the augmented matrix: it sticks the column b to the right of A. And size(A, 2) asks only for the number of columns, which is the number of unknowns.
Here all three are 3: the rank of A equals the rank of the augmented matrix (there is a solution) and equals the number of unknowns (only one). The system has a unique solution.
A detail: rank does not do Gauss like you. It uses another decomposition (the SVD) and counts what is not zero with a tolerance, because on a computer a zero can come out as 0.0000000000000002. That is why it is more reliable than checking whether det(A) == 0. To think about it, keep the idea above: rows that survive.
Check you’ve got it: if you get rank(A) = 2, rank([A b]) = 3 and n = 3, what kind of system is it?
It has no solution. Step by step: the two ranks do not match, and that decides it without looking at n. The augmented matrix having one more rank means that, doing Gauss, a row has become zeros in the A part but not in the b column: an equation like 0 = 5. With 2, 2 and n = 3 it would have infinitely many solutions: the case from my story, further down.
2. The reduced row echelon form: rref
rref runs Gauss-Jordan on the matrix you give it. On the augmented matrix, the last column is the solution:
rref([A b])
Output:
ans =
1 0 0 -2
0 1 0 3
0 0 1 2
Each row reads as an equation: the first says x = −2, the second y = 3 and the third z = 2. It is the same as you would do on paper, just without arithmetic slips: that is why it is useful to check your Gauss by hand.
This is how you get to that matrix. Gauss-Jordan picks up where we left off by hand, at (1, 0, 1 | 0), (0, 3, −2 | 5) and (0, 0, −8 | −16), and does two more things: it makes each pivot 1 and makes zeros above it too.
| Step | Operation | Resulting row | Why |
|---|---|---|---|
| 1 | Row 3 divided by −8 | (0, 0, 1 | 2) | The pivot has to be 1 |
| 2 | Row 2 + 2 · row 3 | (0, 3, 0 | 9) | Removes the z from the second row: −2 + 2 · 1 = 0 |
| 3 | Row 2 divided by 3 | (0, 1, 0 | 3) | Again, pivot to 1 |
| 4 | Row 1 − row 3 | (1, 0, 0 | −2) | Removes the z from the first row: 1 − 1 = 0 |
It is the same as in MATLAB, row by row. Careful: rref does not choose the pivots like you. In each column it brings up the number with the largest absolute value, not the handy 1, because that way rounding grows less. The path is different, but the reduced row echelon form is unique: it ends up in the same place.
To read any rref([A b]), look at three things, in this order:
- Is there a row of zeros with a 1 in the last column? That is 0 = 1: no solution, and stop there.
- Is there a column of A without a pivot? That unknown is free: infinitely many solutions.
- If every column of A has a pivot, the last column is the solution, as here.
3. The solution with the backslash
x = A \ b A*x - b
Output:
x =
-2
3
2
ans =
0
0
0
A\b (“A left-divided into b”) solves A*x = b. Checking A*x - b is a good habit: it has to give the zero vector (or almost, because of rounding).
A\b is better than inv(A)*b: it does fewer operations and makes less rounding error. Use inv only when you are asked for the inverse.
What A\b does inside
The backslash reads as “solve for x in A*x = b”, but MATLAB does not compute any inverse. With a square matrix like A it essentially does what you did: Gauss (as an LU factorisation) and back substitution. With the echelon rows from before:
| Equation (bottom to top) | You solve for | Why in this order |
|---|---|---|
| −8z = −16 | z = 2 | It has only one unknown |
| 3y − 2z = 5 | 3y = 5 + 4 = 9, y = 3 | You already know z: substitute and only y is left |
| x + z = 0 | x = −2 | You already know z: only x is left |
But what A\b does depends on the shape of A, and that explains the surprise in the next section:
| A is… | What A\b does | What it returns |
|---|---|---|
| square and invertible (det ≠ 0) | Gauss and back substitution | the unique solution |
| square and singular (det = 0) | tries and warns: Matrix is singular to working precision. | meaningless numbers (Inf, NaN or very large ones) |
| with more columns than rows | another decomposition (QR) | one of the infinitely many, with zeros in some unknown |
| with more rows than columns | least squares | the one that “fails least”, even if it is not a solution |
Only in the first row does it answer “what is the solution?”. In the others it returns something anyway, and it only warns in the second. That is why you look at the rank first.
When there are infinitely many solutions
Now the case from my story. A system of two equations in three unknowns:
C = [1 1 1; 1 2 3]; d = [6; 14]; rank(C), rank([C d]) x = C \ d
Output:
ans =
2
ans =
2
x =
2.0000
0
4.0000
Both ranks are 2 and there are 3 unknowns: infinitely many solutions, with 3 − 2 = 1 free unknown. And yet C\d returns one specific vector, (2, 0, 4), without any warning. It is one of the infinitely many solutions: the one you get by setting to 0 the free unknown MATLAB picks.
To see all the solutions, the echelon form and the null space:
rref([C d]) N = null(C, 'r')
Output:
ans =
1 0 -1 -2
0 1 2 8
N =
1
-2
1
rrefgives two equations: x − z = −2 and y + 2z = 8. With z = t free: x = −2 + t, y = 8 − 2t, z = t.null(C, 'r')gives a basis of the null space (the solutions ofC*x = 0) with “nice” numbers (the'r'stands for rational): the vector (1, −2, 1).
The general solution is the particular one plus any multiple of the null space: x = (2, 0, 4) + t·(1, −2, 1). Check with t = 2: (4, −4, 6) → 4 − 4 + 6 = 6 and 4 − 8 + 18 = 14. It works.
Trusting A\b without looking at the ranks. If the system has infinitely many solutions, it gives you one without warning; if it has none, it gives you the one that “fails least” (least squares), which is not a solution. Always compare rank(A), rank([A b]) and n first.
null(C) without the 'r' also works, but it gives a vector of length 1 with decimals: with this C, (−0.4082, 0.8165, −0.4082). It is the same vector, with its sign flipped and divided by its norm (√6 ≈ 2.449); to read it in class, the 'r' version is easier.
A line of solutions, point by point
In words, the general solution says: “start from any solution and move along the direction of the null space as much as you like”. The null space is the vectors that C turns into (0, 0): if you add one to a solution, C*x still gives (6, 14). Check it:
C = [1 1 1; 1 2 3]; C*[1; -2; 1] C*[2; 0; 4] C*[-2; 8; 0]
Output:
ans =
0
0
ans =
6
14
ans =
6
14
The null space vector gives (0, 0) and the other two, (6, 14): they are solutions. The third one comes from rref by setting z = 0, the first thing you would do with x − z = −2 and y + 2z = 8; MATLAB, on the other hand, set y to 0. Both are on the same line:
| t | Point (2, 0, 4) + t · (1, −2, 1) | x + y + z | x + 2y + 3z | Who gives it |
|---|---|---|---|---|
| −4 | (−2, 8, 0) | 6 | 14 | rref with z = 0 |
| 0 | (2, 0, 4) | 6 | 14 | C\d, with y = 0 |
| 2 | (4, −4, 6) | 6 | 14 | the check above |
That is why (2, 0, 4) + t · (1, −2, 1) and (−2, 8, 0) + t · (1, −2, 1) are both right: the same line, started at a different point.
Check you’ve got it: is (0, 4, 2) a solution of the system? If it is, which t gives it?
Yes, with t = −2. Step by step: 0 + 4 + 2 = 6 and 0 + 8 + 6 = 14, so it is a solution. For the t, the first coordinate: 2 + t = 0 gives t = −2. With that t, the other two: y = 0 − 2 · (−2) = 4 and z = 4 + (−2) = 2. It works.
Determinant, inverse and eigenvalues
Three functions that come up in almost every AG topic:
det(A) format rat inv(A) format eig([2 1; 1 2])
Output:
ans =
8
ans =
3/8 1/8 1/8
-1/4 1/4 1/4
-3/8 -1/8 7/8
ans =
1
3
det(A)is 8: since it is not 0,Ais invertible (and that is why the first system had a unique solution).inv(A)withformat ratcomes out as fractions, as on paper.eiggives the eigenvalues: for the matrix [2 1; 1 2], 1 and 3. With[V, D] = eig(M)you also get the eigenvectors, in the columns ofV.
det of a matrix that is not square: MATLAB replies Matrix must be square. And a det that is almost 0 (for example -1.2e-16) means the matrix is singular: it is a 0 with rounding noise.
Where the 8, the 1 and the 3 come from
MATLAB gives you the numbers; in the exam you are asked for the working. This is how det(A) comes out, expanding along the first row, with A = [2 −1 0; 1 3 −1; 1 0 1]:
| Entry | Sign | Minor (cross out its row and column) | Determinant of the minor | Contributes |
|---|---|---|---|---|
| 2 | + | [3 −1; 0 1] | 3 · 1 − (−1) · 0 = 3 | 2 · 3 = 6 |
| −1 | − | [1 −1; 1 1] | 1 · 1 − (−1) · 1 = 2 | −(−1) · 2 = 2 |
| 0 | + | [1 3; 1 0] | does not matter | 0 |
6 + 2 + 0 = 8. And that is why inv(A) comes out in eighths: the inverse is the transposed adjugate divided by the determinant. The 3/8 in the corner is the minor of the 2 (which is 3) divided by 8.
The eigenvalues of [2 1; 1 2] are the λ that make det(M − λI) zero. Subtract λ on the diagonal: (2 − λ)(2 − λ) − 1 · 1 = 0, that is, (2 − λ)² = 1. So 2 − λ is 1 or −1, and λ is 1 or 3. It is an equation with a letter: what syms solves, next.
Symbolic maths with syms
Problems like “for which values of a is the system consistent?” cannot be done with numbers: you need MATLAB to work with the letter. That is what the Symbolic Math Toolbox is for (if syms gives an error, you need to install it: it is explained in the installation guide).
syms a M = [a 2; 2 a] det(M) sol = solve(det(M) == 0, a)
Output:
M = [a, 2] [2, a] ans = a^2 - 4 sol = -2 2
syms acreates the symbolic variablea. From then on,Mis a matrix with a letter inside.det(M)gives the expressiona^2 - 4, exactly.solve(det(M) == 0, a)solves the equation: the determinant vanishes for a = −2 and a = 2. Note the==: with a single=it would be an assignment and would fail.
Symbolic output looks different: lines with a space around them and matrices with commas and brackets for each row. That is MATLAB’s format for sym objects.
To study one specific case, subs replaces the letter with a value:
M2 = subs(M, a, 2) rank(M2)
Output:
M2 =
[2, 2]
[2, 2]
ans =
1
With a = 2 the matrix has two equal rows and its rank drops to 1. That is exactly what you have to discuss in a problem with a parameter: for a ≠ ±2 the rank is 2, and for a = ±2 it drops to 1.
| I want to… | Command |
|---|---|
| create a letter | syms a (or syms a b) |
| solve an equation | solve(expression == 0, a) |
| substitute a value | subs(expression, a, 2) |
| simplify | simplify(expression) |
| turn it into a number | double(expression) |
syms, line by line
What each line of the example does, and why:
| Line | What it creates | Why it comes out like that |
|---|---|---|
syms a | the letter a, a symbolic object | Without this line, a would be a variable with no value and would fail |
M = [a 2; 2 a] | a symbolic matrix | One letter inside is enough for the whole matrix to be sym |
det(M) | a^2 - 4 | It does a · a − 2 · 2 with the letter, without rounding anything |
det(M) == 0 | the equation a² − 4 = 0 | With sym, == does not compare: it builds an equation |
solve(…, a) | the column [−2; 2] | Solves for a: a² = 4, so a = −2 or a = 2 |
With that, discussing the parameter takes two steps: solve gives the critical values and subs lets you look at each one, and at one that is not critical:
syms a M = [a 2; 2 a]; rank(subs(M, a, -2)) rank(subs(M, a, 5)) det(subs(M, a, 5))
Output:
ans =
1
ans =
2
ans =
21
With a = −2 the matrix is [−2 2; 2 −2]: the second row is the first with its sign flipped and the rank drops to 1, as with a = 2. With a = 5, the determinant is 25 − 4 = 21 and the rank is 2.
Typing syms a in the Command Window and clicking Run on a script that starts with clear. The clear deletes the symbolic a and M = [a 2; 2 a] gives Unrecognized function or variable 'a'. The syms a goes inside the script, after the clear.
Try it in the MATLAB playground
In the site’s MATLAB playground you can run this script, sections included, with nothing to install:
%% Infinitely many solutions: classify and solve C = [1 1 1; 1 2 3]; d = [6; 14]; ranks = [rank(C), rank([C d]), size(C, 2)] echelon = rref([C d]) nullspace = null(C, 'r') %% Parameter: for which a does the determinant vanish? syms a M = [a 2; 2 a]; values = solve(det(M) == 0, a)
Things to look at:
- Put the cursor in the second section and press Ctrl + Enter: only that part runs.
- In the Workspace,
ranksis [2 2 3]: two equal ranks below 3, infinitely many solutions. - Type
C*([2;0;4] + 5*nullspace)on the>>line and check that it gives (6, 14) for any number instead of the 5. - Click Step by step and watch each variable appear and what each function does.
Summary
| Step | Command | What it tells you |
|---|---|---|
| Classify | rank(A), rank([A b]), size(A, 2) | whether there is a solution and how many |
| Echelon form | rref([A b]) | the equations already solved |
| Solve (if unique) | x = A\b | the solution |
| All the solutions | particular + null(A, 'r') | the general solution |
| Parameters | syms, det, solve, subs | the critical values |
Three ideas to keep:
- Classify first, then solve.
A\balways returns something, even when the solution is not unique. rrefis Gauss-Jordan without arithmetic slips: use it to check what you do by hand.- With letters,
syms: that is what the parameter problems in the assignments ask for.
That is the end of MATLAB from scratch. From here on, each Linear Algebra and Geometry topic comes with its MATLAB code to check the exercises, starting with matrices and determinants.
Keep goingAll MATLAB articlesDid this article help you? Here is how you can support SergioLearns →



