How can I plus two or more strings?
64 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
Ced
le 12 Mar 2016
Modifié(e) : Ced
le 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) = '';
0 commentaires
Steven Lord
le 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'!
0 commentaires
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!