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

23 views (last 30 days)
Oleg Komarov
Oleg Komarov on 12 Apr 2011
Answered: VIGNESH on 30 Apr 2023
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

Accepted Answer

Patrick Kalita
Patrick Kalita on 12 Apr 2011
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
  8 Comments
Patrick Kalita
Patrick Kalita on 12 Apr 2011
My second point is documented here: http://www.mathworks.com/help/techdoc/ref/colon.html
It says "If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1)."
Oleg Komarov
Oleg Komarov on 12 Apr 2011
@Walter: tried to look for 'operator order' and didn't think of 'precedence' (cost of being non-native). Thanks!

Sign in to comment.

More Answers (3)

Sean de Wolski
Sean de Wolski on 12 Apr 2011
And the transpose acts as expected:
>> ((0:n-1)*n)'
ans =
0
4
8
12
>> ans+(1:n)'
ans =
1
6
11
16
  1 Comment
Oleg Komarov
Oleg Komarov on 12 Apr 2011
Here the fact that 1:n is enclosed in parentheses evaluates the addition after the colon expansion.

Sign in to comment.


Sean de Wolski
Sean de Wolski on 12 Apr 2011
I'm able to replicate this. Mac OSX R2009b.
It also fails if I break it between lines:
>> ((0:n-1)*n)
ans =
0 4 8 12
>> ans+1:n
ans =
1 2 3 4

VIGNESH
VIGNESH on 30 Apr 2023
u = 0:1/n:1

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!