Colon-generated arrays with or without brackets
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Rik
le 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 commentaires
Rik
le 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
le 31 Mar 2021
Modifié(e) : Stephen23
le 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!