Issues with The Colon (:) Operator

11 views (last 30 days)
Royi Avital
Royi Avital on 20 May 2015
Commented: Stephen23 on 22 Apr 2020
I have an issue with the colon operator which operates differently than expected.
Let's define the following vectors:
vA = 30:0.0025:60;
vB = 30:0.0025:70;
Now, since their starting point and step size are identical I'd expect their values to match in the overlap zones.
Yet, try this:
a = vA(642);
b = vB(642);
isequal(a, b)
a - b
As one could see, the result is different (46.0249999999 vs. 46.0250000006). This is very different from the documentation of the colon operator .
I was expecting its values no to be dependent on the end value (Only the number of steps depend on the end value).
Is it a bug or am I missing something?
Thank You.

Accepted Answer

Guillaume on 20 May 2015
The behaviour of colon used to be fully documented in older versions and in a technical solution on Mathworks website. Unfortunately, that documentation has been removed in newer versions and the link on Mathworks is dead.
This answer gives you the details.
Basically, with non-integer steps, colon works from both ends to avoid accumulating errors. I can't fathom why Mathworks thinks that information is no longer relevant.
Stephen23 on 22 Apr 2020
The provided links are now dead, but these appear to provide the relevant information:
The original technical explanation (since removed from the TMW website) is archived here:

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by