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 Comment

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!

Sign in to comment.

Answers (2)

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.
Try this:
>> X = {'Apple','Orange','Banana','Fruit'};
>> Y(2,:) = X;
>> Y(1,:) = {' + '};
>> [Y{2:end}]
ans =
Apple + Orange + Banana + Fruit

Categories

Asked:

on 24 Jun 2015

Edited:

on 29 Jun 2015

Community Treasure Hunt

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

Start Hunting!