use of parentheses confusion

1 回表示 (過去 30 日間)
Zhangziyi Zhou
Zhangziyi Zhou 2022 年 2 月 3 日
回答済み: John D'Errico 2022 年 2 月 3 日
how does the code operate differently between first and 2nd line?
10+1:5*3
ans = 1×5
11 12 13 14 15
10+(1:5*3)
ans = 1×15
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

採用された回答

Kevin Holly
Kevin Holly 2022 年 2 月 3 日
In the first line, 10 is added to the 1
so you end up with
11:15 %This creates an array starting from 11 and ending at 15 at increments of 1 (1 is default if not specified
ans = 1×5
11 12 13 14 15
This is the same as
11:1:15 % start:increment:end
ans = 1×5
11 12 13 14 15
The second one creates creates an array from 1 to 15 and then adds 10
1:15 % same as 1:1:15
ans = 1×15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(1:15)+10
ans = 1×15
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

その他の回答 (1 件)

John D'Errico
John D'Errico 2022 年 2 月 3 日
This is a question about operator precedence, and we can find the rules here:
In there, we see that colon operator is quite low on the scale. So it gets evaluated LAST. That means we can view this expression
10+1:5*3
ans = 1×5
11 12 13 14 15
as the same as
(10+1):(5*3)
ans = 1×5
11 12 13 14 15
Whew! I got lucky, and I was correct. MATLAB adds 10+1=11, as the lower limit for colon. The upper limit is 5*3=15.
In the second case, we know that : has the lowest order on that scale. So it will evaluate 5*3 as the upper limit for colon. But how about that 10? The 10 falls outside the parens. And parens is at the very top of the list. So what is inside the parens is evaluated before we add 10 to that result. So this expression generates the list 1:15. Then it adds 10 to every element in the list. So I expect to see the list 10:25 here.
10+(1:5*3)
ans = 1×15
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Again, it works.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by