How to concatenate two newline characters together?
8 views (last 30 days)
Show older comments
MathWorks Support Team
on 5 Mar 2018
Answered: MathWorks Support Team
on 18 Apr 2018
When I use the newline function it returns a new character for newline. However when I try to add two of them together like below, I get an unexpected result. It returns "20".
>> newline + newline
ans =
20
Is there anyway to concatenate those characters together?
Would it be possible to implement a string newline function?
Accepted Answer
MathWorks Support Team
on 5 Mar 2018
The behavior you are seeing is because MATLAB uses the "+" operator as plus operator, and for characters, that means converting them to their ASCII values, in this case "10" and summing those values.
Strings are an exception to this where "s" + "s" will concatenate the strings.
To concatenate two or more characters, I recommend using the "[ ]" bracket syntax. Each character group separated by either spaces or commas inside the brackets will be concatenated together.
So the code below would return what you would expect.
>> res = [newline, newline]
res =
'
'
or
>> res = [newline newline]
res =
'
'
To implement a string version of the newline function, you could write a file called "stringnewline.m" which contains the following:
function out = stringnewline
out = string(newline);
end
If you add that file to the MATLAB path, you will be able to use a string form of the newline function.
0 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!