Fun with linspace and the colon operator in MATLAB
Say you want a vector that starts at 0 and goes to 1 in steps of 0.1
There are two ways you might do this in MATLAB
If you display either x or y then you will get
[0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000]
So it looks like we are in clover. However if we do
[1 1 1 0 1 1 1 1 1 1 1]
Which shows that the vectors x and y are not EXACTLY equal for all values (1 stands for true and 0 stands for false so one value is different). We can see that the difference is extremely small by doing
0 0 0 0.5551 0 0 0 0 0 0 0
This tiny difference is almost certainly caused by the fact that the colon operator and linspace use slightly different methods to calculate the vectors as pointed out in the newsgroup post where I discovered this little piece of trivia. . If floating point arithmetic was exact then it wouldn’t matter what algorithm you used to calculate a vector like this – the result would always be the same as you would expect.
However, floating point arithmetic isn’t exact and so things like the order of operations matters. This sort of thing has been discussed many times by people considerably more erudite than me so I refer you to them for details.
What I was curious about was ‘How,exactly, does the colon operator calculate it’s values and how does this differ from linspace?’ Oh yes, I am a sucker for mathematical trivia.
If I didn’t have access to either of these methods in MATLAB then I would calculate our vector like this
But it turns out that this isn’t equal to either x or y so this isn’t how linspace or the colon operator works:
a==x (compare to colon operator)
1 1 1 1 1 1 0 0 1 1 1
a==y (compare to linspace)
1 1 1 0 1 1 0 0 1 1 1
Another way for calculating this vector that springs to mind is to start with 0 and repeatedly add 0.1 until you reach 1. I normally would never do it like this due to the possibility of accumulating rounding errors on each addition but let’s take a look.
As I’d expect, this isn’t how MATLAB does it either.
b==x (compare to colon operator)
1 1 1 1 1 1 1 1 0 0 0
b==y (compare to linspace)
1 1 1 0 1 1 1 1 0 0 0
My methods don’t agree with each other either (do a==b to see) but I was expecting that.
So, I am non the wiser. How does linspace and the colon operator work? Thoughts and comments would be welcomed.