Can I join variables containing strings into one variable?
显示 更早的评论
Hi,
Say hypothetically, I have a series of a variables containing strings which I got after running a loop. A1 = 'Apple' A2 = 'Orange' A3 = 'Banana' . . . An = 'Fruit'
Is it possible to get a string that would contain the following:
A_Total = 'Apple + Orange + Banana + ... + Fruit' ie. I would also want to see the plus (+) signs
1 个评论
Make you own life easier and store these strings together in one cell array. This avoids the need for poor programming practices like dynamically named variables. Numbered variables are a sign of bad data planning, and these should be rather kept together in one cell array. Read these to know why:
Note that every answer will likely put these in a cell array as the first step... and for a good reason: it is easier to work with!
回答(2 个)
Adam
2015-6-24
strjoin( { A1, A2, A3,..., An }, ' + ' )
would work in the case you give, but you have to hard-code in each of the An.
But that then leads to the question of how/why you end up with such individually named variables as the output from a loop. Ideally they should be in the cell array format into which I pack them to call strjoin anyway if they came from a loop.
Stephen23
2015-6-24
Try this:
>> X = {'Apple','Orange','Banana','Fruit'};
>> Y(2,:) = X;
>> Y(1,:) = {' + '};
>> [Y{2:end}]
ans =
Apple + Orange + Banana + Fruit
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!