MATLAB: How to plus (append) string in each loop

plus string

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'
How can I plus result in each loop, like this:
str='Person A Person B'
Thank for your help!

Best Answer

Here's another one of many ways. Not necessarily the best, but along the lines of what you started with. (Is this homework?)
person=[1, 2];
finalString = ''; % Initialize
for i=1:length(person)
if (person(i))== 1
str=sprintf('Person A');
elseif (person(i))==2
str=sprintf('Person B');
elseif (person(i))==3
str=sprintf('Person C');
elseif (person(i))==4
str=sprintf('Person D');
elseif (person(i))==5
str=sprintf('Person E');
else
str=sprintf('System can not detect!');
end
finalString = [finalString, ' ', str]; % Append this string.
end
fprintf('The final string = %s\n', finalString);
Related Question