Matrices and systems in MATLAB — theory for programming your own Gauss-Jordan, functions with several outputs and the recursive determinant (and the receipt that was five cents out)

Keeping the flat’s shared kitty by hand taught me that copying and pasting row operations does not scale: in the third system I changed a 2 into a 3 and rice came out at −0.80 € a kilo. Laura, Pablo and I shop together and, at the end of the month, someone has always lost the breakdown of a receipt. All that is left is the total and what was in the bag. With three receipts you can set up a system and get the prices back; I used to solve it in a script with ten lines like M(2,:) = M(2,:) - M(2,1)*M(1,:), copied from an AG lab assignment. It worked for that matrix and for no other.

This article is about stopping copying lines and starting to program: writing your own MATLAB functions (with their file, their arguments and several outputs), going through rows and columns with loops, building your own Gauss-Jordan with pivoting, comparing it with rref and with A\b, and computing a determinant by cofactors with a function that calls itself. You already know the algebra: if you need to brush up on row operations, rank or the Rouché-Frobenius theorem, they are in matrices and determinants and in systems of linear equations, and the basics of the language are in MATLAB from scratch and its second part. Here we take all that as read and focus on the code.

In a nutshell: a MATLAB function is an .m file that starts with function [outputs] = name(inputs), has its own variables and returns one or more results. With functions, for loops and if conditions you can program your own Gauss-Jordan, which does the same as rref, and check any result with norm(A*x - b).

Before you start. All you need is to know how to create a matrix in MATLAB and take a row out with M(2, :), and to have done a 3 × 3 Gauss-Jordan by hand in AG. The order: first functions (how you write them and which variables each one sees); then row operations as lines of code and just enough loops; with that, your Gauss-Jordan in three versions; and at the end we use it to compare with MATLAB, decide the kind of system and compute a determinant with recursion. If you get lost, go back to the supermarket receipts: the whole article solves them over and over again.

What you will program and for which topic

The example for the whole article is the flat’s supermarket receipts. We buy three things: rice (per kilo), milk (per litre) and trays of chicken. From three receipts we only kept what was in the bag and the total:

ReceiptRice (kg)Milk (l)Chicken (trays)Total
126112.60 €
214214.00 €
332110.00 €

If aa, ll and pp are the prices, each receipt is an equation (2a+6l+p=12.602a + 6l + p = 12.60…) and the three together form a system Ax=bA\mathbf{x} = \mathbf{b}. Solving it is AG topic 2; programming the machine that solves it is today’s job. By the end of the article you will have:

  • a function gauss_jordan that returns the reduced row echelon form and the pivot columns, like [R, jb] = rref(M);
  • a function solve_system that uses it to tell whether the system has a unique solution, infinitely many or none, and gives a solution;
  • a recursive function det_cofactors that computes the determinant by expanding along the first row and counts how many times it calls itself.

They are for AG topics 1 and 2 and for the lab assignments: instead of one specific matrix, any matrix.

Before the code: the receipts, solved in your head

Before writing a single line, think about how you would get the prices without any algebra. Which receipt would you like to have? One with a single thing on it. If there were a receipt for “1 kg of rice and nothing else”, its total would be the price of rice. You don’t have it, but you can make it by combining the three you do have. With the receipts you can make three moves without the sums stopping being true:

  • Change their order. Writing down receipt 3 first doesn’t change what anything cost.
  • Multiply one by a number. If receipt 1 (2 kg of rice, 6 l of milk and 1 tray) cost 12.60 €, half of everything costs half: 1 kg of rice, 3 l of milk and half a tray, 6.30 €. It isn’t a real shop, but the sum is true.
  • Subtract a multiple of another one. Receipt 2 (1 kg, 4 l, 2 trays, 14.00 €) minus that “half receipt 1” (1 kg, 3 l, half a tray, 6.30 €) gives 0 kg of rice, 1 l of milk and 1.5 trays for 7.70 €. The rice has disappeared from receipt 2.

The third one is the important move: with it you keep removing products until receipt 1 only has rice, receipt 2 only milk and receipt 3 only chicken, and then the totals are the prices. The order is always the same: you leave one receipt with 1 unit of the product whose turn it is, and you use it to wipe that product out of all the others.

You already have the whole method; now, the names from topic 1. The table of quantities with the totals next to it is the augmented matrix (A∣b)(A \mid \mathbf{b}): each row is a receipt, each column a product and the last one, the totals. The three moves are the row operations. The number you turn into a 1 and use to clean its column (the kilo of rice in the “half receipt 1”) is the pivot. And the goal, ones on the diagonal, zeros around them and the prices in the last column, is the reduced row echelon form. Gauss-Jordan is doing this column by column, and the code in this article only writes these three moves in MATLAB.

When a line of code looks abstract to you, translate it into receipts. M(3, :) = M(3, :) - 3*M(1, :) is “take three times the half receipt 1 away from receipt 3”: it removes exactly the 3 kg of rice it had.

Scripts and functions: two kinds of file

MATLAB has two kinds of .m file:

  • A script is a list of instructions. It runs from top to bottom and works with the variables in the Workspace: whatever it creates stays there, and whatever was already there it can overwrite. It is what you used in the lab assignments.
  • A function starts with the word function. It receives data, works with its own variables (which disappear when it finishes) and returns results. It neither sees the Workspace nor clutters it.

The first line of a function says everything you need to use it:

function total = cost(quantities, prices)
% COST  What a shop costs: quantities times prices, added up.
%   total = cost(quantities, prices) with two vectors of the same size.
total = sum(quantities .* prices);
end
  • total is the output: the variable the function must give a value before it finishes.
  • cost is the name: the file must be called the same, cost.m.
  • quantities, prices are the inputs: inside the function they are ordinary variables holding whatever you pass.
  • The % lines just below are the help: help cost shows them.
  • end closes the function.

With the file saved in your working folder, you use it like any MATLAB function:

prices = [1.20 0.95 4.50];
cost([2 6 1], prices)            % receipt 1
t3 = cost([3 2 1], prices);      % with ; it is not shown
t3

Output:

ans =

   12.6000

t3 =

    10

You get 12.60 €, the total of receipt 1, and 10 €, that of receipt 3: with the right prices, the function reproduces the receipts. Notice that inside cost there is no t3 and no script prices (there is one called prices too, but it is a different variable, the one it receives), and outside there is no total: each in its own space. The diagram shows it.

Script and function workspacesThe script tickets.m has prices, t3 and ans in the Workspace; the function cost has quantities, prices and total in its own space; the values go in through the inputs and come back through the output.tickets.m (script)Workspaceprices[1.20 0.95 4.50]t310ans12.6000cost([3 2 1], prices)cost.m (function)its own variablesquantities[3 2 1]prices[1.20 0.95 4.50]total10it disappears at endinputsoutputEach file, its own space: only the inputs and outputs cross over
The prices inside cost is a copy of what you pass: changing it inside does not change the script's one.

You can also write functions inside a script, at the end of the file (since MATLAB R2016b). They are called local functions and only that script sees them. It is the most convenient option for a lab assignment handed in as a single .m. The rule is strict: first all the instructions, then all the functions, each one with its end.

What happens when you call cost, step by step

The “each in its own space” idea is easier to understand by following a whole call. We take the one for receipt 3, t3 = cost([3 2 1], prices);:

StepWhat happensWhy
1MATLAB looks for cost: it isn’t a variable, so it looks for the file cost.m in your folderThe name of the file is the name of the function
2It creates a new, empty workspace for this callThat way the function neither sees nor overwrites anything in the script
3It copies [3 2 1] into quantities and [1.20 0.95 4.50] into the prices insideInputs are matched by position, not by name
4It runs the body: quantities .* prices gives [3.60 1.90 4.50] and sum turns it into 10Inside, the inputs are ordinary variables
5When it reaches the end, it checks the value of total (10) and returns itThe output is whatever total holds at the end
6It deletes the function’s whole workspace: quantities, its prices and total disappearA function’s variables only live while it runs
7In the script, the 10 is stored in t3Whatever is to the left of the = receives the first output

Look at step 3: it doesn’t matter what the thing you pass is called; inside it will always be called prices. And at step 6: if you then type total in the command window, MATLAB will tell you it doesn’t exist.

Check you’ve got it: if you type prices = [1 1 1] and then t = cost([2 6 1], [1.20 0.95 4.50]), what are t and prices in the Workspace?

t is 12.60 and prices is still [1 1 1]. Step by step: the call passes the vector [1.20 0.95 4.50] directly, so the prices inside the function holds that, not [1 1 1]. The function works out 2.40 + 5.70 + 4.50 = 12.60 and returns it to t. The prices in the Workspace plays no part at any point: it has the same name, but it lives in another space, and the function neither reads it nor changes it.

Several outputs and optional arguments

A function can return several things. They go in square brackets, just like in [m, n] = size(A):

function [total, priciest] = analyse_receipt(quantities, prices)
% ANALYSE_RECEIPT  Receipt total and position of the product that took the most money.
spent = quantities .* prices;
total = sum(spent);
[~, priciest] = max(spent);   % ~ discards the first output of max (the value)
end

You call it like any MATLAB function, asking for one or two outputs:

[total, priciest] = analyse_receipt([1 4 2], prices)
total_only = analyse_receipt([1 4 2], prices)

Output:

total =

    14

priciest =

     3

total_only =

    14

On receipt 2 the most expensive thing was the chicken (position 3: 2 × 4.50 = 9 € out of 14). If you ask for a single output, MATLAB gives you the first one. And if you only want the second, [~, priciest] = analyse_receipt(...).

To make an argument optional you use nargin, which inside the function tells you how many inputs you were given. It is the way to give a default value:

function total = cost_tax(quantities, prices, tax)
% COST_TAX  Total with tax; if not given, the 7 % general IGIC rate of the Canary Islands.
if nargin < 3
    tax = 0.07;
end
total = sum(quantities .* prices) * (1 + tax);
end

Two calls, one without the third argument and one with it:

cost_tax([2 6 1], prices)          % with the default 7 %
cost_tax([2 6 1], prices, 0)       % no tax

Output:

ans =

   13.4820

ans =

   12.6000

12.60 × 1.07 = 13.482: the first call uses the default value; the second passes an explicit 0 and gives 12.60 again.

Row operations as lines of code

Every Gauss-Jordan is made of the three row operations from topic 1. In MATLAB, each one is a single line that works on whole rows thanks to ::

OperationOn paperIn MATLAB
SwapR1↔R3R_1 \leftrightarrow R_3M([1 3], :) = M([3 1], :)
Multiply by a numberR2→14R2R_2 \to \tfrac{1}{4} R_2M(2, :) = M(2, :) / 4
Add a multiple of anotherR3→R3−3R1R_3 \to R_3 – 3R_1M(3, :) = M(3, :) - 3*M(1, :)

The swap is the least intuitive: M([1 3], :) are rows 1 and 3 in that order, and they are assigned M([3 1], :), the same rows the other way round. Let us try it with the augmented matrix of the receipts:

A = [2 6 1; 1 4 2; 3 2 1];
b = [12.60; 14.00; 10.00];
M = [A b];               % the augmented matrix (A | b)
M([1 3], :) = M([3 1], :)

Output:

M =

    3.0000    2.0000    1.0000   10.0000
    1.0000    4.0000    2.0000   14.0000
    2.0000    6.0000    1.0000   12.6000

Rows 1 and 3 have swapped places and row 2 is unchanged. Now the pivot of the first column is a 3. And what you need to “make zeros” below it is not a fixed number but whatever each row has: M(k, 1) / M(1, 1). That is the idea that turns ten copied lines into a loop.

Writing M(1, :) = M(3, :); M(3, :) = M(1, :); to swap. The first line has already overwritten row 1, so the second copies row 3 onto itself: you end up with two equal rows. Either do it in one assignment, as above, or with a temporary variable.

Loops and if: just enough to go through a matrix

Block 2 of the intensive course is all about loops. For Gauss-Jordan this is enough:

  • for j = 1:n ... end repeats the body with j taking the values 1, 2, …, n. for k = [1:i-1, i+1:m] also works, going through “every row except i“.
  • if condition ... elseif ... else ... end chooses a path.
  • break leaves the loop and continue jumps to the next pass.
  • size(M, 1) is the number of rows and size(M, 2), the number of columns.

A small example: in which row is the number with the largest absolute value of a column, from row 2 down? We will need it shortly.

col = [0; -7; 3; 5];
[largest, p] = max(abs(col(2:end)))   % p counts from row 2
p = p + 1                              % position in the whole column

Output:

largest =

     7

p =

     1

p =

     2

max with two outputs returns the value and its position, but the position is within the slice col(2:end). Since the slice starts at row 2, you have to add 1 to get the real row. That “plus one” (in general, + row - 1) is one of the most common mistakes when programming Gauss.

Every row except i, pass by pass

From the list above, [1:i-1, i+1:m] is the hardest thing to read, and you will see it in all three versions of Gauss-Jordan. Split it in two: 1:i-1 are the rows above row i, and i+1:m, the ones below. The square brackets join them into a single vector.

What makes it work at the edges is a detail: if the start of a range is greater than its end, as in 1:0 or 4:3, you get an empty vector. And joining an empty vector to another one adds nothing. With m = 3 rows, the three passes are these:

i1:i-1i+1:mk goes throughWhy
11:0, empty2:3, that is [2 3]2 and 3There are no rows above row 1: only the ones below get cleaned
21:1, that is [1]3:3, that is [3]1 and 3One above and one below; row 2 is skipped because it is the pivot row
31:2, that is [1 2]4:3, empty1 and 2There are no rows below the last one

Check it in MATLAB. The last line shows how it writes an empty vector:

m = 3;
for i = 1:m
    rows = [1:i-1, i+1:m]
end
above_row_1 = 1:0

Output:

rows =

     2     3

rows =

     1     3

rows =

     1     2

above_row_1 =

  1×0 empty double row vector

That is why you don’t need any if for the first or the last row: on that side the range comes out empty and the loop doesn’t go round.

And why do you have to skip i? If k could be i, the line M(k, :) = M(k, :) - M(k, i) * M(i, :) would subtract the pivot row from itself multiplied by its 1: it would leave it full of zeros and you would lose the receipt you have just prepared.

The full program: your Gauss-Jordan, from the naive version to the good one

Version 1: the script that copied lines

This is how I used to solve the receipts. It works, but only for this matrix:

M = [A b];
M(1,:) = M(1,:) / M(1,1);             % pivot of column 1 to 1
M(2,:) = M(2,:) - M(2,1)*M(1,:);      % zeros in column 1
M(3,:) = M(3,:) - M(3,1)*M(1,:);
M(2,:) = M(2,:) / M(2,2);             % column 2
M(1,:) = M(1,:) - M(1,2)*M(2,:);
M(3,:) = M(3,:) - M(3,2)*M(2,:);
M(3,:) = M(3,:) / M(3,3);             % column 3
M(1,:) = M(1,:) - M(1,3)*M(3,:);
M(2,:) = M(2,:) - M(2,3)*M(3,:);
prices = M(:, end)'

Output:

prices =

    1.2000    0.9500    4.5000

Rice at 1.20 €/kg, milk at 0.95 €/l and chicken at 4.50 € a tray. Checking by hand with receipt 1: 2⋅1.20+6⋅0.95+1⋅4.50=2.40+5.70+4.50=12.602 \cdot 1.20 + 6 \cdot 0.95 + 1 \cdot 4.50 = 2.40 + 5.70 + 4.50 = 12.60. Good. But look at the pattern: each group of three lines is the same thing with another index. That is a loop asking to come out.

Before turning it into a loop, follow the script with the numbers: each line is one of the receipt moves. The row that changes is written like a receipt, (rice; milk; chicken) and its total.

Line of the scriptThe row becomesWhy
M(1,:) = M(1,:) / M(1,1)R1 = (1; 3; 0.5) → 6.30Divides by 2 to get 1 kg of rice: it is the half receipt 1
M(2,:) = M(2,:) - M(2,1)*M(1,:)R2 = (0; 1; 1.5) → 7.70Receipt 2 had 1 kg of rice: row 1 is subtracted once
M(3,:) = M(3,:) - M(3,1)*M(1,:)R3 = (0; −7; −0.5) → −8.90Receipt 3 had 3 kg: row 1 is subtracted 3 times. Negatives appear: these are sums now, not shopping
M(2,:) = M(2,:) / M(2,2)R2 = (0; 1; 1.5) → 7.70The milk was already 1: nothing changes, but the script does it anyway
M(1,:) = M(1,:) - M(1,2)*M(2,:)R1 = (1; 0; −4) → −16.80Removes the 3 litres of milk from row 1
M(3,:) = M(3,:) - M(3,2)*M(2,:)R3 = (0; 0; 10) → 45.00M(3,2) is −7: subtracting row 2 −7 times is adding it 7 times
M(3,:) = M(3,:) / M(3,3)R3 = (0; 0; 1) → 4.50Only chicken is left: if 10 trays are 45 €, one is 4.50 €
M(1,:) = M(1,:) - M(1,3)*M(3,:)R1 = (1; 0; 0) → 1.20M(1,3) is −4: adds row 3 four times and the chicken disappears
M(2,:) = M(2,:) - M(2,3)*M(3,:)R2 = (0; 1; 0) → 0.95Subtracts row 3 1.5 times

Read the “Why” column from top to bottom: you never have to think about the factor in each subtraction, it is the number that row has in the pivot column, M(k, i).

Version 2: a function with loops (and a hidden flaw)

If the index that changes is the column i, the whole script fits into two loops:

function M = gj_simple(M)
% GJ_SIMPLE  Gauss-Jordan without choosing the pivot: only works if a 0 never shows up on the diagonal.
m = size(M, 1);
for i = 1:m
    M(i, :) = M(i, :) / M(i, i);           % pivot to 1
    for k = [1:i-1, i+1:m]                 % every row except i
        M(k, :) = M(k, :) - M(k, i) * M(i, :);
    end
end
end

We try it on the usual receipts:

gj_simple([A b])

Output:

ans =

    1.0000         0         0    1.2000
         0    1.0000         0    0.9500
         0         0    1.0000    4.5000

Same result, and it works for any size. Until the chicken sneaks into the first receipt. If the receipt you write down first is one with no rice (5 litres of milk and a tray, 9.25 €), the matrix starts with a 0:

T = [0 5 1 9.25; 1 4 2 14; 3 2 1 10];
gj_simple(T)

Output:

ans =

   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

NaN everywhere. In the first pass, M(1, :) / M(1, 1) divides by 0: the 0 gives NaN (0/00/0) and the rest, Inf. After that, every subtraction with Inf spreads it. MATLAB does not raise an error when dividing by zero: it gives you Inf or NaN and carries on, so the failure shows up far from where it starts. On paper you would have seen it in a second: “I swap row 1 with another one that has no 0 there”.

Version 3: with partial pivoting and a tolerance

The good version does what you would do, with two improvements the computer needs:

  1. Partial pivoting: in each column, choose as pivot the number with the largest absolute value among the remaining rows, and move its row up. That way it never divides by 0 if there is an alternative, and it also loses less precision (dividing by very small numbers magnifies rounding errors).
  2. Tolerance: on a computer, a number that should be 0 sometimes comes out as 1e-16. The function treats anything smaller than tol as zero, and if the whole column is “zero”, it moves on to the next one without a pivot. It is what rref does, with the same formula for tol.
function [R, piv] = gauss_jordan(M, tol)
% GAUSS_JORDAN  Reduced row echelon form of M with partial pivoting, like rref.
%   [R, piv] = gauss_jordan(M) returns the reduced matrix and the pivot columns.
%   [R, piv] = gauss_jordan(M, tol) decides what is zero with the tolerance tol.
if nargin < 2
    tol = max(size(M)) * eps(norm(M, inf));   % rref's default tolerance
end
[m, n] = size(M);
R = M;
piv = [];                % the pivot columns get noted down here
row = 1;                 % row where the next pivot goes
for j = 1:n
    if row > m
        break            % no rows left: we are done
    end
    [largest, p] = max(abs(R(row:m, j)));   % the largest of what is left of the column
    p = p + row - 1;                         % position in the whole matrix
    if largest <= tol
        R(row:m, j) = 0;                     % column with no pivot: what is there is noise
        continue
    end
    R([row p], :) = R([p row], :);          % move the pivot row up
    R(row, :) = R(row, :) / R(row, j);      % pivot to 1
    for k = [1:row-1, row+1:m]              % zeros above and below
        R(k, :) = R(k, :) - R(k, j) * R(row, :);
    end
    piv(end+1) = j;                          % note down the pivot column
    row = row + 1;
end
end

The three new pieces, one by one:

  • row and j go separately. In a system with a column without a pivot, the column moves on and the row does not. That is why for i = 1:m, as in version 2, is not enough.
  • eps(norm(M, inf)) is the gap between (roughly) the largest number in the matrix and the next number the computer can represent. Multiplied by the size of the matrix, it gives a threshold that grows with the data: “almost zero” is not the same in a matrix of cents as in one of millions.
  • piv(end+1) = j adds an element at the end of a vector. With piv = [] at the start, the first time it creates it.

With the receipt without rice at the top, the diagram shows what happens in each column:

Your Gauss-Jordan with partial pivotingFour states of the augmented matrix of the receipt without rice: at the start the pivot of column 1 is 0; the function brings up row 3 (pivot 3), then swaps rows 2 and 3 (pivot 5) and finishes with the identity and the prices 1.20, 0.95 and 4.50.startthe 0 would divide0519.251421432110column 1row 3 goes up: pivot 310.670.333.3303.331.6710.670519.25column 2rows 2-3 swap: pivot 5100.22.1010.21.850014.5column 3pivot already in place1001.20100.950014.5Prices: rice 1.20 · milk 0.95 · chicken 4.50
Each column after its row swap and the zeros above and below; numbers rounded to two decimals.
[R, piv] = gauss_jordan(T)

Output:

R =

    1.0000         0         0    1.2000
         0    1.0000         0    0.9500
         0         0    1.0000    4.5000

piv =

     1     2     3

No more NaN: in column 1 the function has moved the 3 up (row 3), and in column 2 it has preferred the 5 to the 3.3333. The prices come out as 1.20, 0.95 and 4.50 again, and piv = [1 2 3] says there is a pivot in the three columns of AA: a consistent system with a unique solution.

Version 3, pass by pass

The diagram shows the matrices; this table, the variables that decide what gets done, which is where you go wrong when you program it. It is the call gauss_jordan(T), with the receipt without rice at the top; T has 4 columns, the 3 for the products and the one for the totals:

jrowWhat it looks atlargestpWhat it doesWhy
11abs of [0; 1; 3], rows 1 to 333Swaps rows 1 and 3, divides row 1 by 3 and makes zeros in rows 2 and 3. Now piv = [1] and row = 2The 3 is the largest: it avoids the 0 and is the safest pivot
22abs of [3.3333; 5], rows 2 and 352 within the slice; 2 + 2 − 1 = 3 in the matrixSwaps rows 2 and 3, divides by 5 and makes zeros in rows 1 and 3. Now piv = [1 2] and row = 3The slice starts at row 2: hence the + row − 1
33abs of [1], row 3 only11 within; 3 in the matrixSwaps row 3 with itself (does nothing), divides by 1 and makes zeros in rows 1 and 2. Now piv = [1 2 3] and row = 4Only one row is left: the pivot is whatever is there, if it isn’t zero
44nothing––breakrow > m: no rows left. The totals column never gets looked at

Here row and j move together because every product column has a pivot. They split as soon as one is left without one: j moves on and row waits.

Check you’ve got it: what does [R, piv] = gauss_jordan([1 1 3; 2 2 6]) return?

R = [1 1 3; 0 0 0] and piv = 1. Step by step: with j = 1 and row = 1, the largest of [1; 2] is the 2, in row 2. It moves it up, divides it by 2 (leaving 1 1 3) and subtracts it from the other row, which becomes all zeros. Now piv = [1] and row = 2.

With j = 2 it looks at column 2 only from row 2 down: there is a 0, which doesn’t exceed tol, so there is no pivot and continue jumps to j = 3 without moving row. With j = 3 it looks from row 2 again and sees a 0 again. The columns run out with a single pivot column. With for i = 1:m, as in version 2, it would have divided 0 by 0 and NaN would come out.

Comparing with what MATLAB has

Your function is worth nothing if it does not match the real one. MATLAB has three ways of getting to the same place: rref, which computes the reduced row echelon form (and also returns the pivot columns), A\b, which solves the system directly, and rank. Comparisons are made with norm of the difference, never with ==:

[R1, piv1] = gauss_jordan([A b]);
[R2, piv2] = rref([A b]);
difference = norm(R1 - R2)
same_pivots = isequal(piv1, piv2)
x = A \ b;
residual = norm(A*x - b)

Output:

difference =

     0

same_pivots =

  logical

   1

residual =

   1.7764e-15

The difference between the two matrices is 0 and the pivots match. The residual of A\b, on the other hand, is 1.7764⋅10−151.7764 \cdot 10^{-15}: A*x does not give exactly b, but b with an error in the fifteenth decimal place. That is normal, because 0.95 cannot be stored exactly in binary (and that exact remainder can change from one computer to another: what matters is that it is of the order of 10−1510^{-15}). That is why a solution is checked with norm(A*x - b) < tol and not with isequal(A*x, b).

To leave the check written into the script itself, assert(norm(A*x - b) < 1e-10, 'The solution does not satisfy the system'). If all is well, it says nothing; if it fails, it stops with your message. In the lab assignments it is a quick way to know you have not used the wrong matrix.

A function that decides the kind of system

With the pivot columns of the augmented matrix you can apply Rouché-Frobenius without computing ranks separately: if the last column (that of b\mathbf{b}) is a pivot column, rank⁡(A)<rank⁡(A∣b)\operatorname{rank}(A) < \operatorname{rank}(A|\mathbf{b}) and the system is inconsistent; if there are as many pivots as unknowns, it has a unique solution; otherwise, infinitely many.

function [x, kind] = solve_system(A, b)
% SOLVE_SYSTEM  Solves A*x = b with gauss_jordan and says what kind of system it is.
%   With infinitely many solutions it returns the one with the free variables set to 0.
n = size(A, 2);
[R, piv] = gauss_jordan([A b]);
if any(piv == n + 1)
    kind = 'inconsistent';
    x = [];
elseif numel(piv) == n
    kind = 'unique solution';
    x = R(1:n, end);
else
    kind = 'infinitely many solutions';
    x = zeros(n, 1);
    x(piv) = R(1:numel(piv), end);   % the pivot ones, from the right-hand side; the free ones, 0
end
end

Let us try it on the three cases. The third case adds a fourth receipt (1 kg of rice, 1 l of milk and 1 tray) written down as 6.70 €, when with the right prices it would be 6.65 €: a five-cent mistake when copying it.

[x, kind] = solve_system(A, b)
[x, kind] = solve_system([1 1; 2 2], [3; 6])
[x, kind] = solve_system([A; 1 1 1], [b; 6.70])

Output:

x =

    1.2000
    0.9500
    4.5000

kind =

    'unique solution'

x =

     3
     0

kind =

    'infinitely many solutions'

x =

     []

kind =

    'inconsistent'

The first one is the usual. The second, two equations that are the same (the second is twice the first), has infinitely many solutions, and the function returns one, x1=3x_1 = 3, x2=0x_2 = 0. And it catches the third: with four receipts and three prices, if one is copied wrong there are no prices that fit all four. It is exactly what Rouché-Frobenius says: rank 3 against rank 4.

In the inconsistent case, returning x with no value. If a function promises an output, it has to give it in every branch of the if, even if it is empty (x = []). Otherwise MATLAB complains when someone asks for it (you will see it in the common mistakes).

A function that calls itself: the determinant by cofactors

Expansion along the first row, from topic 1, says that a determinant of order nn is a sum of nn determinants of order n−1n-1:

∣A∣=∑j=1n(−1)1+j a1j ∣A1j∣ |A| = \sum_{j=1}^{n} (-1)^{1+j}\, a_{1j}\, |A_{1j}|

where A1jA_{1j} is the matrix without row 1 and column jj. Programming it is almost copying the formula, with a recursive function: inside det_cofactors you call det_cofactors with a smaller matrix, until you reach a 1×11 \times 1 one, whose determinant is its only number (the base case). A second output counts the calls:

function [d, calls] = det_cofactors(A)
% DET_COFACTORS  Determinant by expanding along the first row (recursive).
%   [d, calls] = det_cofactors(A) also counts how many times it has been called.
n = size(A, 1);
calls = 1;                       % this call
if n == 1
    d = A(1, 1);                 % base case: the determinant of a number
    return
end
d = 0;
for j = 1:n
    minor = A(2:n, [1:j-1, j+1:n]);       % without row 1 and column j
    [dm, c] = det_cofactors(minor);       % the same function, one order smaller
    d = d + (-1)^(1+j) * A(1, j) * dm;
    calls = calls + c;
end
end

With the receipts matrix:

[d, calls] = det_cofactors(A)
det(A)

Output:

d =

    20

calls =

    10

ans =

    20

It gives 20, the same as det. By hand: 2(4−4)−6(1−6)+1(2−12)=0+30−10=202(4 – 4) – 6(1 – 6) + 1(2 – 12) = 0 + 30 – 10 = 20. And 10 calls: the one for the 3×33 \times 3 matrix, three for 2×22 \times 2 and six for 1×11 \times 1.

Where those 10 calls come from becomes clear by following the recursion. Each 2 × 2 call asks for two 1 × 1 calls and waits for their results to finish its sum:

CallReturnsWhyCalls
det_cofactors(A), 3 × 32 · 0 − 6 · (−5) + 1 · (−10) = 20For each j it removes row 1 and column j and calls itself with what is left1 + 3 + 3 + 3 = 10
Minor for j = 1: [4 2; 2 1]4 · 1 − 2 · 2 = 0Calls itself with [1] and with [2]1 + 1 + 1 = 3
Minor for j = 2: [1 2; 3 1]1 · 1 − 2 · 3 = −5Calls itself with [1] and with [3]3
Minor for j = 3: [1 4; 3 2]1 · 2 − 4 · 3 = −10Calls itself with [2] and with [3]3
Each of the six 1 × 1 callsIts only numberBase case: return leaves before the loop1

The count always follows the same rule, whatever the numbers: a matrix of order n makes its own call and n calls of order n − 1. If you call c(n)c(n) the calls for order n, c(1)=1c(1) = 1 and c(n)=1+n⋅c(n−1)c(n) = 1 + n \cdot c(n-1). So c(2)=1+2⋅1=3c(2) = 1 + 2 \cdot 1 = 3 and c(3)=1+3⋅3=10c(3) = 1 + 3 \cdot 3 = 10.

Check you’ve got it: how many calls will det_cofactors make with a 4 × 4 matrix?
  1. Step by step: the 4 × 4 call counts 1 and asks for four 3 × 3 minors. Each one makes 10 calls, like the receipts matrix. Total: 1 + 4 · 10 = 41. You will see it confirmed in the output below.

The counter has a lesson inside it. Each order multiplies the calls by nn:

for n = 2:7
    [~, c] = det_cofactors(ones(n));
    fprintf('Order %d: %5d calls\n', n, c);
end

Output:

Order 2:     3 calls
Order 3:    10 calls
Order 4:    41 calls
Order 5:   206 calls
Order 6:  1237 calls
Order 7:  8660 calls
Cofactors grow like n!Bar chart on a log scale: calls of det_cofactors for n from 2 to 7 (3, 10, 41, 206, 1237 and 8660) next to n cubed (8, 27, 64, 125, 216 and 343).1101001,00010,00038n = 21027n = 34164n = 4206125n = 51,237216n = 68,660343n = 7det_cofactors callsn³ (elimination, like det)Log scale
The calls come from the program's run; n³ is the order of the operations of an elimination like det's.

With n=7n = 7 it is already 8,660 calls, and with n=10n = 10 it would be over six million (6,235,301). It grows like n!n!. det, on the other hand, does not expand by cofactors: it does an elimination like Gauss’s (an LU decomposition) and multiplies the diagonal, about n3n^3 operations. For a 4×44 \times 4 lab assignment both are fine; to understand why the computer does not work like you do on paper, this counter is the best proof.

When zero is not zero

One last experiment with the order-4 magic square, which is singular (its rows are dependent):

det(magic(4))
det_cofactors(magic(4))

Output:

ans =

   -1.4495e-12

ans =

     0

det gives −1.4495⋅10−12-1.4495 \cdot 10^{-12} and your function gives 0. Both are right in their own way: your expansion only adds and multiplies integers, so the result is exact; the elimination in det divides, and the decimals leave a tiny remainder. That is why “is it singular?” is not asked with det(A) == 0, but with the rank (rank(magic(4)) gives 3, which already uses a tolerance) or with abs(det(A)) < tol.

Common mistakes (with MATLAB’s real message)

These are the ones you will see most when starting with functions. The message is the one MATLAB gives; when the error happens inside a function, MATLAB first adds an Error using … line with the name of the function and the line.

1. An instruction after a local function. In a script, functions go at the end:

x = 1
function y = twice(x)
    y = 2*x;
end
y = twice(3)

Output:

Function definitions in a script must appear at the end of the file. Move all statements after the "twice" function definition to before the first local function definition.

The fix is to move y = twice(3) above the first function.

2. Calling with fewer arguments than the function uses. cost needs both vectors:

cost([2 6 1])

Output:

Not enough input arguments.

If an argument is meant to be optional, check nargin before using it, as in cost_tax.

3. Asking for more outputs than there are. cost only returns one:

[total, other] = cost([2 6 1], prices)

Output:

Too many output arguments.

4. An output that is not filled in on every path. A version of solve_system that forgot the x of the inconsistent case:

function [x, kind] = solve_system_bad(A, b)
n = size(A, 2);
[R, piv] = gauss_jordan([A b]);
if any(piv == n + 1)
    kind = 'inconsistent';          % x is missing!
else
    kind = 'consistent';
    x = R(1:n, end);
end
end

Asking it for both outputs in the inconsistent case:

[x, kind] = solve_system_bad([A; 1 1 1], [b; 6.70])

Output:

Output argument "x" (and possibly others) not assigned a value in the execution with "solve_system_bad" function.

5. An index outside the matrix. Typical of pivoting when the + row - 1 is forgotten or the loop goes one row too far:

A(4, :)

Output:

Index in position 1 exceeds array bounds. Index must not exceed 3.

6. Multiplying with sizes that do not match. b is a column of 3, so b*A is not possible:

b * A

Output:

Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.

You meant A*x (matrix times column) or, if you wanted something else, b'*A.

  • format rat left switched on. If you put format rat in one block to see fractions, everything after it comes out as fractions (and some decimals come out as huge fractions). Go back with format short.
  • The file with a different name. If you save function gauss_jordan in gj.m, MATLAB calls it by the file name and warns you. Always make them match.

Try it in the MATLAB playground

In the site’s MATLAB playground you can run a script with local functions at the end. This is the receipts one, compact:

% Flat receipts: prices with my Gauss-Jordan
A = [2 6 1; 1 4 2; 3 2 1];      % rice, milk, chicken
b = [12.60; 14.00; 10.00];      % totals
R = gj([A b]);
prices = R(:, end)'
check = norm(A*prices' - b)

function M = gj(M)
m = size(M, 1);
for i = 1:m
    [~, p] = max(abs(M(i:m, i))); p = p + i - 1;   % partial pivoting
    M([i p], :) = M([p i], :);
    M(i, :) = M(i, :) / M(i, i);
    for k = [1:i-1, i+1:m]
        M(k, :) = M(k, :) - M(k, i) * M(i, :);
    end
end
end

Things to look at:

  1. Change the order of the receipts (put [0 5 1] and 9.25 in the first row) and check that pivoting sorts it out.
  2. Remove the pivoting (the two lines with p) and run it again: the NaN appear.
  3. Write prices before the R = … line and look at the message: it does not exist yet.
  4. Put x = 1 after the last end: the playground will tell you, like MATLAB, that functions go at the end.

And to see each row operation with exact fractions, there is the Gauss-Jordan step by step simulator.

Summary

PieceWhat it isExample
Function.m file with function, its own variablesfunction total = cost(q, p)
Several outputsIn square brackets; ~ discards one[R, piv] = gauss_jordan(M)
Optional argumentnargin says how many you were givenif nargin < 2, tol = …; end
Local functionAt the end of a script; only that script sees itFirst instructions, then functions
Row operationOne line with whole rowsM([1 3], :) = M([3 1], :)
Partial pivotingChoose the largest in absolute value[~, p] = max(abs(R(row:m, j)))
Comparingnorm of the difference, never ==norm(A*x - b) < 1e-10
RecursionA function that calls itself, with a base casedet_cofactors

Three ideas to take away:

  1. If you copy a line changing an index, it is a loop; if you copy a block, it is a function. The ten-line script and the fifteen-line function do the same, but only the second one is useful tomorrow.
  2. The computer needs what you do without thinking: switching rows when the pivot is 0 and accepting that 10−1610^{-16} is zero. Pivoting and tolerance.
  3. Your function is not finished until you compare it with MATLAB’s (rref, A\b, det) using norm of the difference.

Now it is your turn: in the block 1 exercises of the intensive course you will write your own functions (the inverse by Gauss-Jordan, Cramer’s rule, the rank by counting pivots) with commented solutions, “What is wrong here?” and a cheat sheet.

Did this article help you? Here is how you can support SergioLearns →

Next step: exercisesMatrices and systems in MATLAB — exercises to program your own Gauss-Jordan, a recursive determinant and the shared-flat accounts (and the system I failed in lab assignment 2)Cheat sheet: the block on one page, to reviewCheat sheetLab assignments: the block's functions and a model scriptFor your lab assignments