Colon-generated arrays with or without brackets
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alec Poulin
el 27 de Mzo. de 2018
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 comentarios
Respuesta aceptada
Rik
el 27 de Mzo. de 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 comentarios
Rik
el 31 de Mzo. de 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
el 31 de Mzo. de 2021
Editada: Stephen23
el 31 de Mzo. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!