MATLAB: What you get with: (0:n-1)*n + 1:n

additionbugcolonMATLABplussumunexpected

What you get with:
n = 4;
(0:n-1)*n + 1:n % 1 2 3 4
I was expecting:
(0:n-1)*n + (1:n) % 1 6 11 16

Best Answer

Two things going on here.
1) Addition is done before the colon operator. Compare this:
>> 1 + 1:4
ans =
2 3 4
and this:
>> 1 + (1:4)
ans =
2 3 4 5
That means that (0:n-1)*n + 1 is evaluated to a vector and that vector becomes the first input to another colon operator.
2) When a vector is given to the colon operator, the first element is used:
>> (1:4):3
ans =
1 2 3