How can I plus (append) string in each loop?

5 ビュー (過去 30 日間)
Yen Hai
Yen Hai 2016 年 3 月 12 日
コメント済み: Image Analyst 2016 年 3 月 13 日
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!

採用された回答

Image Analyst
Image Analyst 2016 年 3 月 12 日
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);
  2 件のコメント
Yen Hai
Yen Hai 2016 年 3 月 13 日
Thanks "Image Analyst"! Yes, it's my homework. I am studying about image processing, I have just begun with matlab programming. Hopefully I can get some help from you!
Image Analyst
Image Analyst 2016 年 3 月 13 日
Sure, just ask, but remember to attach your images and explain the larger context of what you want.

サインインしてコメントする。

その他の回答 (1 件)

dpb
dpb 2016 年 3 月 12 日
編集済み: dpb 2016 年 3 月 12 日
I presume output is a typo intending person. But you don't need a loop nor any logical tests at all...
>> people=['A':'Z']; % define population of names from which to pick
>> persons=1:3:8; % chose some arbitrarily
>> sprintf('Person %2c ',people(person))
ans =
Person A Person D Person G
>>
BTW, if don't want the trailing blank or it's a bother, simply wrap with
strtrim(sprintf('Person %2c ',people(person)))
  1 件のコメント
Yen Hai
Yen Hai 2016 年 3 月 13 日
Thanks "dpb"!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by