- 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?
5 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Stephen23
2017 年 9 月 11 日
編集済み: Stephen23
2017 年 9 月 11 日
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.
3 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!