Colon-generated arrays with or without brackets

9 views (last 30 days)
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?

Accepted Answer

Rik
Rik on 27 Mar 2018
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 Comments
Rik
Rik on 31 Mar 2021
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))
Stephen23
Stephen23 on 31 Mar 2021
Edited: Stephen23 on 31 Mar 2021
@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.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Identification in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!