- If there is no space a unary operator has a higher priority than the binary.
- If the operator is only binary then the space is always optional.

# Vector definition, what is expected behavior when separating elements by comma and spaces are used in the expression?

24 views (last 30 days)

Show older comments

I recently found an unexpected behavior in some of my code. When I define a vector:

ind = [1,1+2,3]

Matlab returns (as expected):

ind =

1 3 3

If I am a little loose with my spaces, and say

ind = [ 1 , 1 + 3 , 3 ]

Matlab still returns the expected answer as stated above. However, if I am less consistent with using spaces and define ind as follows:

ind = [1, 1 +2, 3]

Matlab gives me:

ind =

1 1 2 3

I did also test other arithmetic and logical operators like

[1, 1 -2 -2, 3]

ans =

1 1 -2 -2 3 % acts as [1,1,-2,2,3]

[1, 1 -2 + 2, 3]

ans =

1 1 0 3 % acts as [1,1,-2+2,3]

[1, 1 *2 + 2, 3]

ans =

1 4 3 % acts as [1,1*2+2,3]

[1, 1 *2 +2, 3]

ans =

1 2 2 3 % acts as [1,1*2,2,3]

[1, 1 *2 >2, 3]

ans =

1 0 3 % acts as [1,1*2>2,3]

It seems like +- indicates a new element in the array while other arithmetic operations and logical operations do not. So my question is when does Matlab decide how to separate elements in a vector?

I'm using Matlab 9.0.0.341360 (R2016a)

##### 0 Comments

### Accepted Answer

Stephen23
on 11 Sep 2017

Edited: Stephen23
on 11 Sep 2017

This is explained in the MATLAB documentation:

And has also been covered several times on this forum, e.g.:

Really the differences between your examples come down to whether an operator can be both unary and binary (e.g. + and -) or is binary only (e.g. * and <):

NOTE: All of the examples are code that should never be used in real life. Always use commas for separating elements of an array, if only because it makes the intention clear.

### More Answers (0)

### See Also

### Categories

### Products

### Community Treasure Hunt

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

Start Hunting!