How can I plus two or more strings?
39 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Antworten (2)
Ced
am 12 Mär. 2016
Bearbeitet: Ced
am 12 Mär. 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) = '';
0 Kommentare
Steven Lord
am 12 Mär. 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'!
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!