Appending mixed types to strings seems a bit tricky. Is this the intended behaviour?
3 ビュー (過去 30 日間)
古いコメントを表示
I understand why I get different results, but is seems wrong. Is this intended?
'1' + "1" + 1
'1' + 1 + "1"
0 件のコメント
採用された回答
Rik
2022 年 9 月 27 日
編集済み: Rik
2022 年 9 月 27 日
It helps to do this step by step, which show that (while unintuitive), this is intended behavior.
Matlab evaluates code from left to right:
'1' + "1"
ans + 1
And your second example:
'1' + 1
ans + "1"
Because the first call to plus doesn't know you want to use a string as an operand later, this results in a conversion to double, and since the UTF-16 encoding of '1' is uint16(49), this results in double(50).
You can avoid this by putting in some parentheses:
'1' + ( 1 + "1" )
6 件のコメント
Stephen23
2022 年 9 月 27 日
"I never considered that code is strictly evaluated left to right."
This is explained in the MATLAB documentation: "Within each precedence level, operators have equal precedence and are evaluated from left to right". Plusses all have the same precedence.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!