Colon-generated arrays with or without brackets
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alec Poulin
am 27 Mär. 2018
Bearbeitet: Stephen23
am 31 Mär. 2021
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?
0 Kommentare
Akzeptierte Antwort
Rik
am 27 Mär. 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 Kommentare
Rik
am 31 Mär. 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
am 31 Mär. 2021
Bearbeitet: Stephen23
am 31 Mär. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!