Message Boards Message Boards

GROUPS:

Insert or Joint a element in a table

Posted 5 years ago
8624 Views
|
7 Replies
|
9 Total Likes
|

Hi, I have a this data table

a = { { {a,b},{c,d},{e,f} } , { {1,2},{3,4},{5,6} } }

and

t = {x , z }

I would obtain this

b = { { {a,b,x},{c,d,x},{e,f,x} } , { {1,2,z},{3,4,z},{5,6,z} } }

I have tried with Insert and joint but unsucesfully. Any suggestions please? Thank you

Margherita

7 Replies
Posted 5 years ago

A couple of hints that should be enough to send you in the right direction.

Side note: giving the same name to your list a as some of your elements inside that list is going to cause you problems. Why?

Your first challenge is to associate each element of t with the right list of lists in a. Look up MapThread and contemplate.

Your second challenge is to then use that association to accomplish your goal. Look up Map and contemplate creating a "helper function" that might correctly use that.

That should be enough for you to be able to figure this out on your own now and without anyone giving away an answer.

Posted 5 years ago

delete

I renamed the a and b on the left side to avoid recursion and used rules to perform the transformations. Look up Rule, and Replace for more insight.

Kind regards, David

In[1]:= aa = {{{a, b}, {c, d}, {e, f}}, {{1, 2}, {3, 4}, {5, 6}}};

In[2]:= t = {x, z};

In[3]:= bb = {
  aa[[1]] /. {e1_, e2_} -> {e1, e2, t[[1]]},
  aa[[2]] /. {e1_, e2_} -> {e1, e2, t[[2]]}
  }

Out[3]= {{{a, b, x}, {c, d, x}, {e, f, x}}, {{1, 2, z}, {3, 4, z}, {5, 6, z}}}

Ooops, that is a tricky one!

aa = {{{a, b}, {c, d}, {e, f}}, {{1, 2}, {3, 4}, {5, 6}}};
t = {x, z};

Flatten /@ # & /@ Thread /@ Thread[{aa, t}]

... well, I prefer Davids solution!

Henrik

Flatten always scares me with regards to scalability, thus I prefer

Append @@@ # & /@ Thread /@ Transpose[{aa, t}]

Here probably the same question: How to insert elements of a list into list of lists?

MapThread[Flatten /@ Thread[{##}] &, {aa, t}]
{{{a, b, x}, {c, d, x}, {e, f, x}}, {{1, 2, z}, {3, 4, z}, {5, 6, z}}}

Thank you a lot !

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract