0

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?

(I am using Matlab R2017b 9.3.0.713579)

1

A good answer came from Rik Wisselink on this forum: https://www.mathworks.com/matlabcentral/answers/391046-colon-generated-arrays-with-or-without-brackets

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).

Stephen Cobeldick adds that this is explained by the fact that + has a higher priority than :.

Steven Lord also comments that the transition from line 4 to 5 is explained in the documentation:

If you specify nonscalar arrays, then MATLAB interprets j:i:k as j(1):i(1):k(1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.