Colon-generated arrays with or without brackets

From what I can tell, the arrays a:d:b and [a:d:b] are exactly the same thing. For example,
>> [1:3] == 1:3
ans =
1×3 logical array
1 1 1
Yet, these two expressions give different results:
>> [1:3]' + 1:3
ans =
2 3
>> [1:3]' + [1:3]
ans =
2 3 4
3 4 5
4 5 6
Why?

 采纳的回答

The reason for this is the unexpected order in which this statement is evaluated:
[1:3]' + 1:3
([1:3]' + 1):3
([1;2;3]+1):3
[2;3;4]:3
2:3
[2,3]
Adding the brackets forces the grouping before and after the colon operator (parentheses would have worked as well).

9 个评论

Note that this occurs because plus has a higher priority than the colon:

Maybe 'unexpected' is a poor word choice, but I could think of another phrasing that didn't make me sound like a belittling jerk. But yeah, that page is useful information.

I would have expected this to return an error: the doc doesn't describe that it even supports a vector input as the first argument to colon, but apparently it does and it just picks the first element.

It's easy to overlook, but it is in the documentation. In the second item in the Description section: "If you specify nonscalar arrays, then MATLAB interprets j:i:k as j(1):i(1):k(1)."

Thanks, I was looking for it in the Input Arguments section
I've informed the documentation staff that the description of this behavior was difficult to find. In the future, you can go to the bottom of the documentation page and click on the No button next to "Was this topic helpful?" On the form that comes up, describe what you were expecting to find on the documentation page but couldn't (or if there are errors on the page, or if you think there is a way to improve the way the topic was presented to make it easier to understand, etc.) I know the documentation staff reads that feedback.
@Steven Lord: even better would be to change the colon function so that it throws an error for non-scalar inputs.
An error might break poorly coded functions that rely on this behavior. I think an mlint warning and warning when running the code would be better. If you use it as a shortcut, it will still work, but users will be warned about possibly unintended consequences. (similar to how if a<b<c triggers an mlint warning, but will run if you actually meant to use it like that (e.g. with a custom class that overloads lt))
@Rik: I suspect there is more code broken by this "feature" and time wasted debugging this rather unintuitive behavior, than gained by a few instances where it has been used intentionally (I do not recall ever seeing this).
MATLAB has tweaked other syntaxes over the years, this one is overdue for its retirement too.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Data Type Identification 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by