Appending mixed types to strings seems a bit tricky. Is this the intended behaviour?

조회 수: 4 (최근 30일)
I understand why I get different results, but is seems wrong. Is this intended?
'1' + "1" + 1
ans = "111"
'1' + 1 + "1"
ans = "501"

채택된 답변

Rik
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 = "11"
ans + 1
ans = "111"
And your second example:
'1' + 1
ans = 50
ans + "1"
ans = "501"
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" )
ans = "111"
  댓글 수: 6
Stephen23
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.
Tomazz
Tomazz 2022년 9월 27일
Sure, it makes sense.
Still, I was a bit surprised that (S1+S2)+S3 is not equal to S1+(S2+S3) in this case.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by