6

Suppose I have some array

 A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

For each list, I want to add element a0 at the beginning so that my output is

 {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

Without explicitly typing the first entries, how one can implement this? Further, what if I want to instead add some element at the end?

phy_math
  • 873
  • 4
  • 9

7 Answers7

10
Prepend[a0] /@ A1

{{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

Also:

PadLeft[A1, {Automatic, 3}, a0]

Or:

A1 /. {a_, b_} :> {a0, a, b}

And the new ReplaceAt:

ReplaceAt[A1, x_ :> Sequence[a0, x], {All, 1}]
eldo
  • 67,911
  • 5
  • 60
  • 168
9
A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

Join[{a0}, #] & /@ A1
Catenate[{{a0}, #}] & /@ A1
Replace[A1, {x__} :> {a0, x}, 1]
Transpose@Join[{ConstantArray[a0, Length@A1]}, Transpose@A1]
SequenceCases[A1, {{a_, b__} ..} :> {a0, a, b}]

{{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

Syed
  • 52,495
  • 4
  • 30
  • 85
8

Join has also a (rarely used) last integer argument:

A1 = {{a1, b1}, {a2, b2}, {a3, b3}};

Join[ConstantArray[a0, {3, 1}], A1, 2]

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
7

Here are some ways:

{a0, ##} & @@@ A1
Prepend[#, a0] & /@ A1
Insert[#, a0, 1] & /@ A1
ArrayPad[A1, {{0}, {1, 0}}, a0]

All yield: {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}}

ubpdqn
  • 60,617
  • 3
  • 59
  • 148
7
 ArrayFlatten[{{a0,A1}}]

(* {{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}} *)
user1066
  • 17,923
  • 3
  • 31
  • 49
7

Another one

A1 = {{a1, b1}, {a2, b2}, {a3, b3}};
lista0 = Table[a0, {i, 1, Length@A1}];
ArrayReshape[Flatten[Transpose[{lista0, A1}]], {Length@A1, Length@A1}]
bmf
  • 15,157
  • 2
  • 26
  • 63
4

Another way using Cases:

Cases[A1, x_List :> Join[{a0}, x]]

({{a0, a1, b1}, {a0, a2, b2}, {a0, a3, b3}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44