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

I understand why I get different results, but is seems wrong. Is this intended?
'1' + "1" + 1
ans = "111"
'1' + 1 + "1"
ans = "501"

 Accepted Answer

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 Comments

Yes, I already understood why the results are the way they are, and thank you for very clear explanation. But before running into the issue, I never considered that code is strictly evaluated left to right. It seemed more intuitive to me that when appending strings with "+" operator, all terms were converted to strings before concatenation.
If you want to forget about this behavior, just make sure to always start with a string, even if it is empty:
"" + '1' + 1 + "1"
ans = "111"
"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.
Sure, it makes sense.
Still, I was a bit surprised that (S1+S2)+S3 is not equal to S1+(S2+S3) in this case.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2022b

Asked:

on 27 Sep 2022

Commented:

on 27 Sep 2022

Community Treasure Hunt

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

Start Hunting!