Adding array create via colon operator.

In cleaning up some code, the editor identified some supposedly unnecessary brackets that turned out to be completely necessary (at least parentheses). However, removing them gave some unexpected results. I was wonder if anyone had an explanation for the following example or is it a bug? FYI, I am using Matlab 2011a.
>> x = [1 2 3 4];
>> y = x + [1:4] %with brackets
y =
2 4 6 8
>> y = x + 1:4 %w/o brackets or parentheses
y =
2 3 4
Granted parentheses also work correctly in the first equation ... However, why is the 2nd output only 3 elements? What is Matlab actually doing in that example?
Thanks,

 Respuesta aceptada

Sean de Wolski
Sean de Wolski el 31 de Mzo. de 2014
Editada: Sean de Wolski el 31 de Mzo. de 2014
It's grouping it like this:
(x+1):2
Best practice is to always use parenthesis! So for your example
x + (1:4)
The []s are unnecessary here because they are horizontally concatenating the vector that is already a row vector (the same as [1 2 pi]). Parenthesis don't specify concatenation but do specify order of operations.

1 comentario

Ben
Ben el 31 de Mzo. de 2014
Thanks! That does appear to be what it is doing. I could not see how it was coming up that 3 element answer.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

Ben
el 31 de Mzo. de 2014

Comentada:

Ben
el 31 de Mzo. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by