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

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

 採用された回答

Patrick Kalita
Patrick Kalita 2011 年 4 月 12 日

2 投票

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 件のコメント

Oleg Komarov
Oleg Komarov 2011 年 4 月 12 日
What about the behaviour that Sean outlined for column vector against row colon expansion with no brackets?
Is this behaviour documented?
Matt Fig
Matt Fig 2011 年 4 月 12 日
Sean de only points out the addition of two column vectors.
Patrick Kalita
Patrick Kalita 2011 年 4 月 12 日
@Oleg, I'm not sure what you're referring to. Sean's example shows one column vector being generated by the first statement. Then it is added to another column vector in the second statement. It is the same as your second statement but it uses column vectors instead of row vectors.
Oleg Komarov
Oleg Komarov 2011 年 4 月 12 日
@Matt, Patrick: right! I read column vectors but decided subconsciously to make it more complicated.
Oleg Komarov
Oleg Komarov 2011 年 4 月 12 日
Still can't find where this behavior is documented...
Walter Roberson
Walter Roberson 2011 年 4 月 12 日
Oleg, with the various comments at various times, I am not certain which behaviour it is you are asked about the documentation for?
http://www.mathworks.com/help/techdoc/matlab_prog/f0-40063.html#f0-38155 shows that addition is done before colon.
Patrick Kalita
Patrick Kalita 2011 年 4 月 12 日
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 2011 年 4 月 12 日
@Walter: tried to look for 'operator order' and didn't think of 'precedence' (cost of being non-native). Thanks!

サインインしてコメントする。

その他の回答 (3 件)

Sean de Wolski
Sean de Wolski 2011 年 4 月 12 日

1 投票

And the transpose acts as expected:
>> ((0:n-1)*n)'
ans =
0
4
8
12
>> ans+(1:n)'
ans =
1
6
11
16

1 件のコメント

Oleg Komarov
Oleg Komarov 2011 年 4 月 12 日
Here the fact that 1:n is enclosed in parentheses evaluates the addition after the colon expansion.

サインインしてコメントする。

Sean de Wolski
Sean de Wolski 2011 年 4 月 12 日

0 投票

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 2023 年 4 月 30 日

0 投票

u = 0:1/n:1

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

製品

質問済み:

2011 年 4 月 12 日

回答済み:

2023 年 4 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by