2
$\begingroup$

This seems like something simple but I can't find the answer.

If I have as input:

{{1, 2}, {3, d}} /. d -> {4, -4}

Mathematica outputs:

{{1, 2}, {3, {4, -4}}}

(which is logical as it simply replaces d with the list given)

What I'd like is the following output, i.e., a new list of complete 2x2 matrices:

{{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}}

To give a bit more context, I have two lists of matrices that I'd like to multiply to give all the combinations, e.g.:

list1 = {A,B,C}
list2 = {D,E}

into

{A.D,A.E,B.D,B.E,C.D,C.E}

I already found this trick:

Dot @@@ Tuples[{list1, list2}]

But prior to multiplying the list I need to do a replace all as described above to produce the actual matrices to multiply together.

Thanks

$\endgroup$

2 Answers 2

1
$\begingroup$

You can just use Table:

Table[{{1, 2}, {3, d}}, {d, {4, -4}}]
(* {{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}} *)
$\endgroup$
1
  • $\begingroup$ Knew it had to be simple, thank you $\endgroup$ Nov 16, 2018 at 17:50
1
$\begingroup$
rules =  List /@ Thread[d -> {4, -4}]

{{d -> 4}, {d -> -4}}

{{1, 2}, {3, d}} /. rules

{{{1, 2}, {3, 4}}, {{1, 2}, {3, -4}}}

Note: With a list of rules ReplaceAll uses the first matching rule:

x /. {x -> 1, x -> a, x -> 2}

1

To apply each rule separately, you need to wrap each rule with List:

x /. {{x -> 1}, {x -> a}, {x -> 2}}

{1, a, 2}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.