MATLAB from scratch — the Command Window, vectors and matrices (and the dot that changes everything)
In my first AG lab I wanted the squares of 1, 2 and 3, typed [1 2 3]^2 and MATLAB threw a three-line error at me: the problem was a missing dot. MATLAB thinks in matrices, and squaring a vector “as a matrix” makes no sense; what I wanted was [1 2 3].^2, cell by cell. This article is about exactly that: how MATLAB thinks, so that the matrices of Linear Algebra and Geometry stop giving you scares.
If you have not installed it yet, start with the guide to installing MATLAB with the ULPGC licence. And if you are on your phone or on a library computer, everything here works in the site’s MATLAB playground, with nothing to install.
In a nutshell: MATLAB from scratch means learning to use the Command Window as a matrix calculator: you create vectors and matrices with square brackets, read a cell with A(row, column) and choose between the matrix product (*) and the cell-by-cell one (.*). With that you can already check your AG exercises.
Table of Contents
Before you start. You do not need to have programmed before for this article. All you need is to know what a matrix is in AG: a table of numbers with rows (the horizontal ones) and columns (the vertical ones), where a cell is named by giving its row first and then its column. The path has three stretches, in this order: first you use MATLAB as a calculator and store results in variables; then you build vectors and matrices and learn to point at a cell, a row or a column; and finally comes the idea that decides everything, which is that MATLAB has two ways of multiplying and tells them apart with a dot. If you get lost, go back to the story at the start: the whole article is there to explain why [1 2 3]^2 fails.
The Command Window: a calculator with memory
Open MATLAB and look at the pane called Command Window. That >> is MATLAB waiting for a command. Type a calculation and press Enter:
3 + 4*2 2^10 sqrt(16)
Output:
ans =
11
ans =
1024
ans =
4
Three things you can already see here:
- It respects the usual precedence: first
4*2, then the addition. That is why you get 11 and not 14. ansis the variable where MATLAB stores the last result that had no name. It is overwritten by every calculation.- Each result comes with a blank line before and after. That is MATLAB’s format; you do not need to copy it in the exam, but that is how you will see it on your screen.
Variables and the semicolon
A variable is created with =. If you end the line with ;, MATLAB does the calculation but does not show it:
x = 5 y = 2*x; y
Output:
x =
5
y =
10
y = 2*x; printed nothing, but y exists: when you type its name, MATLAB shows it. You will use this in every script: a semicolon on the set-up lines and none on what you want to see.
The Workspace pane shows every variable with its value and size. If a calculation gives something odd, look there before typing it again.
MATLAB is case-sensitive: A and a are two different variables. If you type a and it says Unrecognized function or variable ‘a’, you probably created it as A.
Vectors: the basic building block
A row vector is written in square brackets with the numbers separated by spaces (or commas). A column vector, with semicolons between the numbers:
v = [3 1 4 1 5] w = [2; 7; 1]
Output:
v =
3 1 4 1 5
w =
2
7
1
The semicolon inside the brackets means “new row”. It is the same symbol as the end-of-line one, but here it hides nothing: it separates rows.
Ranges with a colon
To avoid typing the numbers one by one, start:end creates the list of integers, and start:step:end changes the step. linspace(a, b, n) spreads n points between a and b:
1:5 0:0.5:2 linspace(0, 1, 5)
Output:
ans =
1 2 3 4 5
ans =
0 0.5000 1.0000 1.5000 2.0000
ans =
0 0.2500 0.5000 0.7500 1.0000
Notice that 0:0.5:2 and linspace(0, 1, 5) come out with four decimals: as soon as there is a non-integer, MATLAB shows the whole row in the same format (and the 0 without decimals, because it is exact).
How MATLAB builds a range, number by number
A range is not magic: MATLAB starts at the start value and keeps adding the step as long as it does not go past the end. With 0:0.5:2:
| Step | Number it tries | Does it go in? | Why |
|---|---|---|---|
| 1 | 0 | yes | It is the start: it always goes in if it does not exceed the end |
| 2 | 0 + 0.5 = 0.5 | yes | 0.5 does not go past 2 |
| 3 | 1 | yes | 1 does not go past 2 |
| 4 | 1.5 | yes | 1.5 does not go past 2 |
| 5 | 2 | yes | It lands exactly on the end, and the end counts |
| 6 | 2.5 | no | It goes past 2: this is where it stops |
That is why you get five numbers. If the step does not fit exactly, the end is left out without warning: 0:0.5:1.8 stops at 1.5.
linspace thinks the other way round: you tell it how many points you want and it works out the step. With linspace(0, 1, 5) there are five points, but between five points there are only four gaps, so each gap is . That gives you the 0, 0.25, 0.5, 0.75 and 1 in the output.
Thinking that linspace(0, 1, 5) goes up in steps of 0.2. That would be dividing by 5, and you would get six points. Count the gaps, not the points: with n points there are n − 1 gaps.
Check you’ve got it: what does 10:-3:1 give?
10 7 4 1. Step by step: it starts at 10; the step is −3, so each time it subtracts 3; 7 and 4 are still above the end; 1 is exactly the end and goes in; the next one would be −2, which goes past it (with a negative step, “going past” means ending up below), so it stops there.
Reading and changing a cell
MATLAB indices start at 1, not at 0 as in Python or C. end means “the last position”:
v(2) v(end) v([1 3]) v(2) = 10
Output:
ans =
1
ans =
5
ans =
3 4
v =
3 10 4 1 5
v([1 3]) asks for several positions at once and returns another vector. And v(2) = 10 changes only that cell: the rest of v stays the same.
v(0) does not exist. MATLAB replies Array indices must be positive integers or logical values. If you come from Python, this is the mistake you will make most in your first week.
Position versus value, command by command
The vector v = [3 1 4 1 5] has a trap: its values are small numbers, just like its positions, and it is easy to mix one up with the other. What goes inside the parentheses is always a position. These are the four commands from before, one at a time:
| Command | What it returns | Why |
|---|---|---|
v(2) | 1 | Position 2 holds the 1 (the 3 is in position 1) |
v(end) | 5 | v has five cells, so end is 5, and position 5 holds a 5 |
v([1 3]) | 3 4 | They are not “the values 1 and 3”: they are positions 1 and 3, which hold the 3 and the 4 |
v(2) = 10 | v = 3 10 4 1 5 | It writes into position 2 and leaves the others as they were |
The last command does not come out as ans: when you assign, MATLAB shows you the whole variable you have just changed.
If in doubt, read the parentheses out loud as “what is in position…”. v([1 3]) is “what is in positions 1 and 3”.
Check you’ve got it: after v(2) = 10, what does v([2 end]) give?
10 5. Step by step: v is now 3 10 4 1 5; position 2 holds the 10 you have just written; end is still 5, because changing a cell does not change how many there are, and position 5 still holds the 5. You get a vector with both, in the order you asked for them.
Matrices: rows separated by semicolons
A matrix is a vector of rows. This is the coefficient matrix we will use throughout the article:
A = [2 -1 0; 1 3 -1; 1 0 1] size(A)
Output:
A =
2 -1 0
1 3 -1
1 0 1
ans =
3 3
size(A) returns two numbers: rows and columns. It is the first thing worth checking when an operation complains about dimensions.
Indexing a matrix
With two indices, row first and then column. A colon : on its own means “all of them”:
A(2,3) A(:,2) A(end,:)
Output:
ans =
-1
ans =
-1
3
0
ans =
1 0 1
The drawing shows which cells each command takes. A(:,2) comes out as a column because it really is a column, and A(end,:) as a row.
| I want… | I write | I get |
|---|---|---|
| one cell | A(2,3) | a number |
| a whole column | A(:,2) | a column vector |
| a whole row | A(1,:) | a row vector |
| the last row | A(end,:) | a row vector |
| a block (rows 1-2, columns 2-3) | A(1:2, 2:3) | a 2×2 matrix |
How MATLAB reads A(:,2), step by step
When you write two indices, MATLAB asks two separate questions: which rows you want and which columns you want. It keeps the cells where they cross. A colon on its own answers “all of them”, and end answers “the last one” of whatever that slot refers to. With the article’s A:
| Command | Rows it takes | Columns it takes | Result | Why |
|---|---|---|---|---|
A(2,3) | row 2: 1 3 -1 | column 3 | −1 | One crossing, one cell: the third number of the second row |
A(:,2) | all: 1, 2 and 3 | column 2 | −1, 3, 0 as a column | : in the first slot is “all rows”; from each one it keeps the second number |
A(end,:) | row 3 | all: 1, 2 and 3 | 1 0 1 as a row | In the first slot, end is the last row, because that slot is the one for rows |
A(1:2, 2:3) | rows 1 and 2 | columns 2 and 3 | -1 0; 3 -1 | 2 rows by 2 columns: four crossings, as a 2×2 matrix |
The shape of the result comes from the command itself. If you ask for many rows and one column, you get a column; if you ask for one row and many columns, a row.
Writing A(3,2) when you wanted row 2 and column 3. MATLAB does not complain, because cell (3,2) exists, and it gives you a 0 instead of the −1. Row first, always.
Ready-made matrices
In AG you will use the transpose and the identity a lot. The transpose is written with a quote after it:
A' eye(3) zeros(2,3)
Output:
ans =
2 1 1
-1 3 0
0 -1 1
ans =
1 0 0
0 1 0
0 0 1
ans =
0 0 0
0 0 0
A' swaps rows and columns: the first row of A (2, −1, 0) is now the first column. eye(3) is the 3×3 identity (the name is a pun on how I sounds) and zeros(2,3) a matrix of zeros with 2 rows and 3 columns; ones does the same with ones.
The dot that changes everything: * versus .*
Before looking at any output, think about what multiplying two tables of numbers could mean. There are two reasonable answers. The first: each cell times the one in the same place in the other table. The second, the AG one: each cell of the result comes from running along a row of the first and a column of the second.
Both make sense and give different things, so MATLAB cannot guess which one you want. Since MATLAB was born for matrix algebra (its name comes from MATrix LABoratory), the usual symbol is the algebra one. For the other one you have to give a warning, and the warning is a dot in front.
Here is the mistake from my first lab. Let us take a second matrix:
B = [1 0 2; 0 1 0; 3 0 1]; A*B A.*B
Output:
ans =
2 -1 4
-2 3 1
4 0 3
ans =
2 0 0
0 3 0
3 0 1
They are two different operations:
A*Bis the matrix product from algebra: each cell comes from multiplying a row ofAby a column ofB. Cell (1,1) is 2·1 + (−1)·0 + 0·3 = 2, and (1,3) is 2·2 + (−1)·0 + 0·1 = 4. It matches the output.A.*Bmultiplies cell by cell: (1,1) is 2·1 = 2, (1,3) is 0·2 = 0 and (3,1) is 1·3 = 3.
There is a way of reading A*B that saves you work: by columns. Column j of the result is what you get by applying A to column j of B. And the columns of this B are very simple:
Column of B | What it asks of A | Column of A*B | Why |
|---|---|---|---|
| 1: (1, 0, 3) | column 1 of A once and column 3 three times | (2, −2, 4) | (2, 1, 1) + 3·(0, −1, 1) = (2, −2, 4) |
| 2: (0, 1, 0) | only column 2 of A | (−1, 3, 0) | A 1 and two zeros: it copies column 2 of A as it is |
| 3: (2, 0, 1) | column 1 twice and column 3 once | (4, 1, 3) | 2·(2, 1, 1) + (0, −1, 1) = (4, 1, 3) |
The three columns match the output. In A.*B there is nothing to run along: each cell only looks at its partner, which is why wherever B has a 0 the result has one too.
A consequence that comes up every week in AG: order matters in * and does not matter in .*.
A = [2 -1 0; 1 3 -1; 1 0 1]; B = [1 0 2; 0 1 0; 3 0 1]; B*A B.*A
Output:
ans =
4 -1 2
1 3 -1
7 -3 1
ans =
2 0 0
0 3 0
3 0 1
B.*A is the same as A.*B; B*A is a different matrix, because now the rows are those of B and the columns those of A.
Check you’ve got it: where does the 4 in cell (1,1) of B*A come from?
From row 1 of B times column 1 of A. Step by step: row 1 of B is (1, 0, 2); column 1 of A is (2, 1, 1); you multiply in pairs and add up: 1·2 + 0·1 + 2·1 = 4. In A*B it was 2 because a different row and a different column crossed there.
Powers work the same way. A^2 is A*A (matrix product) and A.^2 raises each cell:
A^2 A.^2
Output:
ans =
3 -5 1
4 8 -4
3 -1 1
ans =
4 1 0
1 9 1
1 0 1
Check it with one cell: in A^2, (1,1) is row 1 of A times its column 1: 2·2 + (−1)·1 + 0·1 = 3. In A.^2 it is simply 2² = 4.
And now the error from my story. A 1×3 row vector cannot be multiplied by itself as a matrix (you would need 1×3 times 3×1), so ^2 makes no sense:
[1 2 3]^2
Output:
Incorrect dimensions for raising a matrix to a power. Check that the matrix is square and the power is a scalar. To operate on each element of the matrix individually, use POWER (.^) for elementwise power.
What I wanted was .^:
[1 2 3].^2
Output:
ans =
1 4 9
Now the whole story can be told with sizes. The matrix product only works if the number of columns of the first equals the number of rows of the second, because each row has to pair up number by number with each column. With v = [1 2 3], which is 1×3:
| Command | Sizes | Result | Why |
|---|---|---|---|
v^2 (that is v*v) | 1×3 times 1×3 | error | The rows of v have 3 numbers and its columns only 1: they cannot be paired up |
v*v' | 1×3 times 3×1 | 1×1 | Now they fit (3 with 3): a row times a column gives a single number |
v'*v | 3×1 times 1×3 | 3×3 | They fit too (1 with 1), and the result takes the rows of the first and the columns of the second |
v.^2 | cell by cell | 1×3 | It pairs nothing up: it raises each number on its own |
v = [1 2 3]; v*v' v'*v v.^2
Output:
ans =
14
ans =
1 2 3
2 4 6
3 6 9
ans =
1 4 9
v*v' gives 14, which is 1 + 4 + 9: the sum of the squares, not the squares. And v'*v is the times table of 1, 2 and 3. Only v.^2 gives what I wanted in that lab.
Fixing the dimensions error by putting a quote mark where it does not belong. v*v' no longer complains, but it gives you a number that is not what you were after. Before fixing anything, ask yourself whether you wanted algebra or cell by cell.
The rule to remember: no dot, algebra; with a dot, cell by cell. In AG you almost always want the matrix product (*), and the dot only for tables of values, such as evaluating a function at many points.
| Operation | No dot (algebra) | With a dot (cell by cell) |
|---|---|---|
| product | A*B: row times column | A.*B: same position |
| power | A^2 = A*A (square A) | A.^2: each cell squared |
| division | A/B solves a system | A./B: each cell over its partner |
| addition and subtraction | A+B | (no dot needed: it is already cell by cell) |
How numbers look: format
By default MATLAB shows four decimals (format short). In AG it is very handy to see everything as fractions, like on paper:
x = 1/3 format rat x inv(A) format long pi format
Output:
x =
0.3333
x =
1/3
ans =
3/8 1/8 1/8
-1/4 1/4 1/4
-3/8 -1/8 7/8
ans =
3.141592653589793
format ratwrites each number as the simplest fraction close to it. It is perfect for comparing with your work by hand: the inverse ofAcomes out with 3/8, −1/4… instead of 0.3750, −0.2500.format longshows 15 decimals.formaton its own goes back to the normal format.
format rat only changes how the number looks, not the number. x is still 0.333… with all its decimals; if you want truly exact fractions, that is symbolic maths, which we cover in the second part of MATLAB from scratch.
format rat stays on until you type format. If suddenly everything comes out as odd fractions like 355/113, you forgot to turn it off.
Why the inverse comes out in eighths
With format rat, every cell of inv(A) comes out with denominator 8 or 4, and it is no coincidence. In AG you saw that the inverse is the transposed adjugate divided by the determinant. The cells of the adjugate are determinants of pieces of A, which only has integers, so they are integers. If the determinant is 8, everything comes out in eighths, and −1/4 is just −2/8 simplified. Check it:
A = [2 -1 0; 1 3 -1; 1 0 1]; det(A) format rat 8*inv(A)
Output:
ans =
8
ans =
3 1 1
-2 2 2
-3 -1 7
The determinant comes out as 8, just as by hand: expanding along the first row, . And multiplying the inverse by 8 leaves the integers of the transposed adjugate. In the exam this works as an alarm: if by hand you get denominators that do not divide the determinant, one of your calculations is wrong.
When format rat shows you an inverse, multiply it by det(A). If you get integers, you have got it; and those integers are what you should have written on paper before dividing.
Functions you will use all the time
A handful of functions cover most one-off calculations:
v = [3 1 4 1 5]; numel(v) sum(v) max(v)
Output:
ans =
5
ans =
14
ans =
5
| Function | What it does | Example |
|---|---|---|
size(A) | rows and columns | size(A) → 3 3 |
numel(v) | number of elements | 5 |
sum, max, min | sum, maximum and minimum (by columns in a matrix) | sum(v) → 14 |
sqrt, abs | square root and absolute value, cell by cell | sqrt(16) → 4 |
A' | transpose | |
eye(n), zeros(m,n), ones(m,n) | identity, zeros and ones | |
help name | the help for a function | help rref |
On a matrix, sum(A) adds up each column and returns a row vector; to add up everything, sum(A(:)). A(:) puts every cell into a single column, going through the matrix column by column.
sum and max on a matrix, column by column
With a vector, sum and max do what you expect. With a matrix, MATLAB thinks in columns again: it does the calculation on each column separately and gives you one result per column. With the article’s A:
| Command | Result | Why |
|---|---|---|
sum(A) | 4 2 0 | Column 1: 2 + 1 + 1; column 2: −1 + 3 + 0; column 3: 0 − 1 + 1 |
A(:) | 2, 1, 1, −1, 3, 0, 0, −1, 1 as a column | It goes down column 1, then column 2 and then column 3 |
sum(A(:)) | 6 | It is now a single vector: it adds up the nine cells, 4 + 2 + 0 |
min(A) | 1 −1 −1 | The smallest in each column |
Notice the order of A(:): it does not read the matrix row by row, like a book, but column by column, which is how MATLAB stores it internally.
Check you’ve got it: what does max(A) give?
2 3 1. Step by step: it does not look for the largest in the whole matrix, but in each column; in column 1 (2, 1, 1) the largest is 2; in column 2 (−1, 3, 0) it is 3; in column 3 (0, −1, 1) it is 1. If you wanted the largest of all, you would write max(A(:)), which gives 3.
Try it in the MATLAB playground
In the site’s MATLAB playground you can run all of this with nothing to install (and from your phone). Paste this script and click Run:
% Vectors and matrices: a recap of the whole article A = [2 -1 0; 1 3 -1; 1 0 1]; B = [1 0 2; 0 1 0; 3 0 1]; row2 = A(2,:) product = A*B cellwise = A.*B format rat inverse = inv(A) format
Things to look at:
- In the Workspace you will see
A,B,row2,product,cellwiseandinversewith their sizes. Clickinverseto see it in full. - The two variables with a semicolon (
AandB) do not appear in the Command Window, but they are in the Workspace. - Change
A.*BtoA.^2and run it again: check one cell by hand. - Type
inverse*Aon the>>line at the bottom: it should give you the identity. If you see1.0000and the odd0.0000instead of 1 and 0, it is not an error: they are tiny leftovers of the computer’s rounding, not exact zeros.
Summary
| Idea | How to write it |
|---|---|
| Row / column vector | [3 1 4] / [2; 7; 1] |
| Matrix | [2 -1 0; 1 3 -1; 1 0 1] |
| Cell, column, row | A(2,3), A(:,2), A(1,:) |
| Indices | start at 1; end is the last position |
| Hide the output | ; at the end of the line |
| Algebra versus cell by cell | *, ^, / versus .*, .^, ./ |
| Fractions | format rat (and format to go back) |
Three ideas to keep:
- MATLAB thinks in matrices. A number is a 1×1 matrix and almost everything works the same with vectors and matrices.
- The dot decides the operation: no dot, algebra; with a dot, cell by cell.
format ratis your best friend in AG for comparing with your work by hand, but it only changes how the number looks.
In the second part we move on to what the assignments ask for: scripts with sections, solving a system with rank, rref and A\b, and symbolic maths with syms.
Did this article help you? Here is how you can support SergioLearns →



