Puzzling syntax: 2:4:6:8:10:12
조회 수: 6 (최근 30일)
이전 댓글 표시
Dear Matlab-profis and beginners,
What do you expect as result of this:
a = 2:3:4:5:6:7
And this:
b = 2:3:4:5:6:7:8
What reasons do you have for your assumptions?
Letting Matlab find the results is too easy. But even if you do, do you have good arguments for the results? Btw, The results are equal for 6.5, 2009a and 2011b.
댓글 수: 0
채택된 답변
Daniel Shub
2013년 5월 29일
The documentation lists the colon operator as having the 6th highest precedence and says that
Within each precedence level, operators have equal precedence and are evaluated from left to right
What is not clear from the precedence documentation is if a:b:c has one or two colon operators. The documentation for the colon operator says
To generate a series that does not use the default of incrementing by 1, specify an additional value with the colon operator (first:step:last).
which suggests to me that a:b:c is a single colon operation (I think this is probably the weakest aspect of the documentation).
The documentation of the colon function says
COLON(J,K) is the same as J:K and COLON(J,D,K) is the same as J:D:K.
I interpret "the same" to me that the converse is also true and that J:K is the same as colon(J,K) and J:D:K is the same as colon(J,D,K).
Based on this I would assume a left to right substitution of triplets.
a = 2:3:4:5:6:7
= colon(2,3,4):5:6:7
= 2:5:6:7
= colon(2,5,6):7
= 2:7
= colon(2,7)
= [2,3,4,5,6,7]
b = 2:3:4:5:6:7:8
= colon(2,3,4):5:6:7:8
= 2:5:6:7:8
= colon(2,5,6):7:8
= 2:7:8
= colon(2,7,8)
= 2
For the additional case given in the comment to IA's answer of 2:3:6:7 we need a little more of the documentation
If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).
a = 2:3:6:7
= colon(2,3,6):7
= [2, 5]:7
= colon(2, 7)
= [2,3,4,5,6,7]
댓글 수: 3
Daniel Shub
2013년 5월 31일
I am a little surprised that "2." is valid. This leads to even odder constructs like 2.e2 and 2..*2.
추가 답변 (1개)
the cyclist
2013년 5월 29일
I would expect MATLAB to interpret this left-to-right, grouping in the form
M:I:N
where possible, so
a = 2:3:4:5:6:7
= (2:3:4):5:6:7
= 2:5:6:7
= (2:5:6):7
= 2:7
= [2 3 4 5 6 7]
and
b = 2:3:4:5:6:7:8
= (2:3:4):5:6:7:8
= 2:5:6:7:8
= (2:5:6):7:8
= 2:7:8
= 2
This is what I get in R2013a.
댓글 수: 3
the cyclist
2013년 5월 29일
As mentioned by Daniel in his answer, your comment that b is ignored seems to be mentioned in the documentation:
If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1).
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!