MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How can I concatenate elements

  • To: mathgroup at
  • Subject: [mg119924] Re: How can I concatenate elements
  • From: Stefan Salanski <wutchamacallit27 at>
  • Date: Wed, 29 Jun 2011 05:31:18 -0400 (EDT)
  • References: <iu4a05$jpm$>

On Jun 25, 5:32 am, "Leandro Tenfen" <leandroten... at>
> Hi,
> I have two lists:
> s1={1,2,3,4,5,6};
> s2={c,k};
> How can I concatenate elements of lists as follows:
> s3={1c,2c,3c,4c,5c,6c,1k,2k,3k,4k,5k,6k}
> Many Thanks!

It looks like Outer is the function which fits your problem best. Just
use StringJoin as your product function.
To use StringJoin, you will need to have both lists be lists of
strings, so {"1", "2", "3", ..etc... } not just {1,2,3...}, and
{"c","k"} not just {c,k}.

In[21]:= s1 = ToString /@ Range[6];
            s2 = {"c", "k"};

In[23]:= Flatten@Outer[StringJoin, s1, s2]

Out[23]= {"1c", "1k", "2c", "2k", "3c", "3k", "4c", "4k", "5c", "5k",
"6c", "6k"}

if you want the resulting list in the order you specified, you can
either sort that list.. though you'd have to sort it starting from the
end of the string, so like
In[24]:= StringReverse /@ Sort[StringReverse /@ %]

Out[24]= {"1c", "2c", "3c", "4c", "5c", "6c", "1k", "2k", "3k", "4k",
"5k", "6k"}

Or you can just switch the order of the lists in Outer, and the order
of the elements passed to StringJoin like this:

In[25]:= Flatten@Outer[StringJoin[#2, #1] &, s2, s1]

Out[25]= {"1c", "2c", "3c", "4c", "5c", "6c", "1k", "2k", "3k", "4k",
"5k", "6k"}

Hope that helps

-Stefan Salanski

  • Prev by Date: Re: Table with conditions
  • Next by Date: Re: Problem with Compile
  • Previous by thread: Re: How can I concatenate elements
  • Next by thread: HDF5