Add text to string in for-loop

42 ビュー (過去 30 日間)
Bas
Bas 2016 年 12 月 2 日
コメント済み: Bas 2016 年 12 月 2 日
Hi,
I would like to add text to a string in a for-loop.
In the end the string should be: str= X(1)+X(2)+X(3)+X(4)....+X(150).
This is my code:
counter = 1;
for i= 1:150
if counter == 1
str= sprintf(' X(%04d) ',i);
else
str= sprintf(' + X(%04d) ',i);
end
counter= counter + 1;
end
However, this results in str= " +X(150)" only instead of the entire sequence.
Can anyone help me with this?

採用された回答

Adam
Adam 2016 年 12 月 2 日
編集済み: Adam 2016 年 12 月 2 日
You need to concatenate( in the else as you currently have it):
str = [str sprintf(' + X(%04d) ',i)];
Why do you have the counter variable though? You already have a loop variable i that can do this. Though personally I would initialise the string with the unique first case outside of the loop. There's no need to test whether you are on the 1st iteration every single iteration of the loop when you know for sure it will only be true the first time. The performance cost is minimal here, but still, you don't want to do things in a loop that don't need to be done in a loop, as general good practice.
  1 件のコメント
Bas
Bas 2016 年 12 月 2 日
Thanks! I actually got more than 1 for-loop, but described only one for simplicity..

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

その他の回答 (1 件)

Guillaume
Guillaume 2016 年 12 月 2 日
If you have matlab R2016b, creating your string is extremely easy using the new string class and associated functions compose and join:
str = join(compose('X(%d)', 1:150), ' + ')
just one line!
  1 件のコメント
Bas
Bas 2016 年 12 月 2 日
Thanks! Still didn't got 2016 installed on this desktop..

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by