0
$\begingroup$

I have an array bs that contains many indexed elements b[ ]. I want to define the values of bs by a list of replacement rules. However replacement does not work. It works only if I replace every element individually that is not comfortable if you have many variables.

bs = Array[b, 10]
rule1 = bs -> {2, 4, 1, 1, 5, 2, 6, 2, 5, 2}
(* {b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8],b[9],b[10]}->{2,4,1,1,5,2,6,2,5,2} *)

b[1] /. rule1
(* b[1] *)

rule2 = {b[1] -> 2, b[2] -> 4};
b[1] + b[2] /. rule2
(* 6 *)

Summary of solutions for different cases (almost all were given in the answers)

If we have 1 list we can replace by

Thread[bs -> {2, 4, 1, 1, 5, 2, 6, 2, 5, 2}].

If we have to replace 2 lists we can do

rule = Flatten@{Thread[bs -> {2, 4}], Thread[as -> {5, 6}]}

If we want to replace a multidimensional list we can use

rule=Thread[Flatten[cs] -> Flatten[{{1,2},{3,4}}]]

and everything together

rule = Flatten@{Thread[bs -> {2, 4}], Thread[as -> {5, 6}],Thread[Flatten[cs] -> Flatten[{{1,2},{3,4}}]]}

$\endgroup$
2
  • 1
    $\begingroup$ Is this approach "comfortable" for your problem ? : Thread[bs -> {2, 4, 1, 1, 5, 2, 6, 2, 5, 2}] ? $\endgroup$
    – andre314
    Oct 20, 2022 at 21:17
  • $\begingroup$ Works. Comfortable. Thanks! $\endgroup$ Oct 20, 2022 at 21:18

1 Answer 1

2
$\begingroup$

However how to define the replacement from 2 lists?

bs = Array[b, 2];
as = Array[a, 2];
rule = Flatten@{Thread[bs -> {2, 4}], Thread[as -> {5, 6}]};
b[1] + a[1] /. rule

7

$\endgroup$
2
  • $\begingroup$ How to treat 2-dimensional lists? See Edit2. $\endgroup$ Oct 20, 2022 at 22:13
  • 1
    $\begingroup$ @granularbastard if I understand correctly you found out how to do it. I just wanted to mention that ArrayReshape is also useful :) $\endgroup$
    – bmf
    Oct 20, 2022 at 22:37

Your Answer

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

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