How to generate string without space at the beginning?
3 次查看(过去 30 天)
显示 更早的评论
FieldsLetter = repmat('Item_',16,1);
FieldsDigit = num2str(transpose(2:2:16),'%1d');
Fields = strcat(FieldsLetter, FieldsDigit);
The result from above code is Fields =
Item_ 2
Item_ 4
Item_ 6
Item_ 8
Item_10
Item_12
Item_14
Item_16
But what I want is Fields =
Item_2
Item_4
Item_6
Item_8
Item_10
Item_12
Item_14
Item_16
So how to generate string by using num2str without the space at the beginning? Thank you.
0 个评论
采纳的回答
Kelly Kearney
2014-11-20
Easier, you can just add the string part to the num2str format:
Fields = num2str((2:2:16)', 'Item_%d');
Of course, this right-justifies the final results, which may or may not matter to you. If you're looking to get a cell array of strings eventually, you can quickly trim the extra whitespace:
Fields = strtrim(cellstr(num2str((2:2:16)', 'Item_%d')))
0 个评论
更多回答(2 个)
Star Strider
2014-11-20
Change '%1d' to '%-1d'. The ‘-’ in front of the format descriptor left-justifies it.
FieldsLetter = repmat('Item_',8,1);
FieldsDigit = num2str(transpose(2:2:16),'%-1d');
Fields = strcat(FieldsLetter, FieldsDigit);
0 个评论
per isakson
2014-11-20
编辑:per isakson
2014-11-20
num2str creates a rectangular character array. The "extra" space can be moved to the end of the string. If that's ok
Replace
FieldsDigit = num2str(transpose(2:2:16),'%1d');
by
FieldsDigit = num2str(transpose(2:2:16),'%-2d');
And read the documentation on num2str. Note:
'–' Left-justify. Example: %-5.2f
An alternative is to insert a leading zero
FieldsDigit = num2str(transpose(2:2:16),'%02d');
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!