How can I plus two or more strings?

69 views (last 30 days)
Yen Hai
Yen Hai on 12 Mar 2016
Answered: Steven Lord on 12 Mar 2016
I have:
person=[1,2];
for i=1:length(person)
if (person(i))== 1
str=sprintf('Person A');
elseif (output(i))==2
str=sprintf('Person B');
elseif (output(i))==3
str=sprintf('Person C');
elseif (output(i))==4
str=sprintf(' Person D');
elseif (output(i))==5
str=sprintf('Person E');
else
str=sprintf('System can not detect!');
end
end
% How can I plus result in each loop, like this:
str='Person A Person B'
Thank for your help!

Answers (2)

Ced
Ced on 12 Mar 2016
Edited: Ced on 12 Mar 2016
Version 1:
You can concatenate two strings like matrix elements, i.e.
str1 = 'Person A ';
str2 = 'Person B ';
str = [ str1 str2 ]
Version 2: Since you are not actually using the output, I would do:
person = [ 1 2 ];
str_all = {'Person A ', 'Person B ', 'Person C ', 'Person D ', 'Person E '};
str = [ str_all{person} ];
No need for any loop or if statements.
If the last space bothers you, just remove it at the end with
str(end) = '';

Steven Lord
Steven Lord on 12 Mar 2016
Some languages use + to concatenate strings. In MATLAB, however, you concatenate character arrays the same way you concatenate other types of arrays: using square brackets.
x = 1:5;
y = 6:10;
z = [x, y] % 1:10
w1 = 'abra';
w2 = 'cadabra';
w = [w1, w2] % 'abracadabra'!

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!